Why does this code throw a NumberFormatException
:
String binStr = "1000000000000000000000000000000000000000000000000000000000000000";
System.out.println(binStr.length());// = 64
System.out.println(Long.parseLong(binStr, 2));
Why does this code throw a NumberFormatException
:
String binStr = "1000000000000000000000000000000000000000000000000000000000000000";
System.out.println(binStr.length());// = 64
System.out.println(Long.parseLong(binStr, 2));
Largest long value is actually:
1000000000000000000000000000000000000000000000000000000000000000
is larger thanLong.MAX_VALUE
.See https://stackoverflow.com/a/8888969/597657
Consider using
BigInteger(String val, int radix)
instead.EDIT:
OK, this is new for me. It appears that
Integer.parseInt(binaryIntegerString, 2)
andLong.parseLong(binaryLongString, 2)
parse binary as sign-magnitude not as a 2's-complement.Because it's out of range.
1000...000
is 263, butLong
only goes up to 263 - 1.This is the largest possible long (9223372036854775807 = 2 exp 63 - 1) in binary format. Note the L at the end of the last digit.
This is because Long.parseLong cannot parse two's complement representation. The only way to parse two's complement binary string representation in Java SE is BigInteger:
this gives expected -9223372036854775808result
This is the same for all of
Long
,Integer
,Short
andByte
. I'll explain with aByte
example because it's readable:The digits are interpreted unsigned, no matter what radix is provided. If you want a negative value, you have to have the minus sign at the beginning of the String. JavaDoc says:
In order to get
MAX_VALUE
we need: