Why does Java offend my use of Long.parseLong (String s, int radix) with this long binary number?

I have the following code:

Why Java thinks this is not a valid long .

 @Test public void testOffendingBinaryString() { String offendingString = "1000000000000000000010101000000000000000000000000000000000000000"; assertEquals(64, offendingString.length()); Long.parseLong(offendingString, 2); } 
+7
source share
6 answers

Because it is out of range for the actual value of long. Line:

 "-111111111111111111101011000000000000000000000000000000000000000" 

should work fine. You cannot specify a negative number directly in 2s to complement binary notation . And if you are trying to specify a positive number, this number is too large to fit in long Java, which is a signed 64-bit value expressed in 2s add-on (which means that basically it is 63 bits + sign bit (this is a bit more complicated, read page on supplement 2s)).

+5
source

long is stored in 2 compliments, but the parsing method expects a direct binary. Thus, the maximum number of digits in a String can be 63.

When using a regular binary file, there is no sign bit. You can pass it a String length 63 and in front of it - if you want a negative long .

+1
source

This is a bug in Java, see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269 , they fixed it in 1.8

+1
source

Java long type:

8 bytes are recorded (two additions). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

0
source

Row size too long check question

0
source

Internal numbers are represented using Two Supplements . This means that there are only 63 bits, since the number and one bit are positive or negative numbers. Since Long.parseLong() does not apply to parsing numbers in two additions, your string is a positive number with 64 bits, which exceeds the maximum positive value for long .

0
source

All Articles