Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: Long.parseLong(s,16) and Long.toHexString(l) not inverses?

I get this but yet I don't get it:

package com.example.bugs;

public class ParseLongTest {
    public static void main(String[] args) {
        long l = -1;
        String s = Long.toHexString(l);
        System.out.println(s);
        long l2 = Long.parseLong(s, 16);
    }   
}

This fails with the following:

ffffffffffffffff
Exception in thread "main" java.lang.NumberFormatException: For input string: "ffffffffffffffff"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:410)
    at java.lang.Long.parseLong(Long.java:468)
    at com.example.bugs.ParseLongTest.main(ParseLongTest.java:8)

presumably because if you literally interpreted 0xffffffffffffffffL, it would not fit in the Long number space, which is signed.

But why does Long.toHexString() produce a string that cannot be parsed by Long.parseLong(), and how do I work around this? (I need a way of getting long values to their hex string representation, and back again)

like image 236
Jason S Avatar asked Mar 17 '11 18:03

Jason S


2 Answers

Long.parseLong(String s, int radix) doesn't understand two's complement. For negative number it expects minus sign. As bestsss already mentioned you should use Long.toString(long l, int radix) to make hex string compatible with this parsing method.

like image 170
hoha Avatar answered Nov 15 '22 21:11

hoha


This is a known bug, it is fixed in 1.8, see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269

like image 25
Evgeniy Dorofeev Avatar answered Nov 15 '22 21:11

Evgeniy Dorofeev