Java: Long.parseLong (s, 16) and Long.toHexString (l) are not accessed?

I get this, but still I don't understand:

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:

 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 interpret 0xffffffffffffffffL, it won't fit in the long number space that will be signed.

But why does Long.toHexString () create a string that cannot be parsed by Long.parseLong (), and how do I get around this? (I need a way to get long values ​​in their hexadecimal representation and vice versa)

+7
source share
3 answers

Long.parseLong(String s, int radix) does not understand two additions. For a negative number, he expects a minus sign. As mentioned above, you should use Long.toString(long l, int radix) to make the hexadecimal string compatible with this parsing method.

+6
source

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

+4
source

You can use guava UnsignedLongs.parseUnsignedLong(String s, int radix) if Java 1.8 is not an option.

+2
source

All Articles