I have the following code:
Why does Java think that this is not a valid long
.
@Test
public void testOffendingBinaryString() {
String offendingString = "1000000000000000000010101000000000000000000000000000000000000000";
assertEquals(64, offendingString.length());
Long.parseLong(offendingString, 2);
}
Because it's out of range for the valid value of a long. The string:
"-111111111111111111101011000000000000000000000000000000000000000"
should work just fine. You cannot specify a negative number directly in 2s complement binary notation. And if you're trying to specify a positive number, that number is too big to fit into a Java long, which is a signed 64-bit value expressed in 2s complement (which means it's basically 63 bits + a sign bit (it's a little more complicated than that, read the page on 2s complement)).
The long
is stored in 2's compliment, but the parse method expects straight binary. So, the max number of digits in the String
can be 63.
When using regular binary, there is no sign bit. You can pass it a String
with length 63 and precede it with a -
if you want a negative long
.
This is a bug in Java, see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269, they fixed it in 1.8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With