java: Long.parseLong(s,16) and Long.toHexString(l) not inverses?
I get this but yet I do开发者_运维问答n'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)
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.
This is a known bug, it is fixed in 1.8, see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269
You can use guava's UnsignedLongs.parseUnsignedLong(String s, int radix)
if Java 1.8 is not an option.
精彩评论