Why is Java offended by my use of Long.parseLong(String s, int radix) with this long binary number?
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.parseL开发者_如何学JAVAong(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
Java long type:
8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
The size of the string is too long, check this question
Internally numbers are represented using the Two's complement. That means there are only 63 bits, for the number and one bit to represent positive or negative numbers. Since Long.parseLong()
is not ment to parse numbers in Two's complement your String is a positive number with 64 bits, that exceeds the maximum positive value for a long
.
精彩评论