Eduardo Dennis Eduardo Dennis - 24 days ago 6
Java Question

Why am I getting a value back from Long.parseUnsignedLong when I shouldn't be

When I do

Long.parseUnsignedLong("FBD626CC4961A4FC", 16)


I get back
-300009666327239428


Which seems wrong, since the meaning of unsigned long according to this answer http://stackoverflow.com/a/2550367/1754020 is that the range is always positive.

To get the correct number from this HEX value I do

BigInteger value = new BigInteger("FBD626CC4961A4FC", 16);


When I print value it prints the correct value. but if I do
value.longValue()


again I get the same
-300009666327239428
is this of the number being too big and overflowing ?

Answer

Java 8 does (somewhat) support unsigned longs, however, you can't just print them directly. Doing so will give you the result that you saw *.

If you have an unsigned long

Long number = Long.parseUnsignedLong("FBD626CC4961A4FC", 16);

you can get the correct string representation with the function

String numberToPrint = Long.toUnsignedString(number);

If you now print numberToPrint you get

18146734407382312188

*To be more exact, your number is still going to be a regular signed long which is why it shows overflow if printed directly. However, there are new static functions that will treat the value as if it was unsigned, such as this Long.toUnsignedString(long x) or Long.compareUnsigned(long x, long y).