Jason S
Jason S

Reputation: 189646

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)

Upvotes: 9

Views: 6694

Answers (3)

Eric
Eric

Reputation: 842

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

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

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

Upvotes: 4

hoha
hoha

Reputation: 4428

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.

Upvotes: 7

Related Questions