7

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);
}
Omnifarious
  • 54,333
  • 19
  • 131
  • 194
kungfoo
  • 1,297
  • 1
  • 14
  • 27

6 Answers6

4

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)).

Omnifarious
  • 54,333
  • 19
  • 131
  • 194
1

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

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.

jjnguy
  • 136,852
  • 53
  • 295
  • 323
0

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.

Sarwar Erfan
  • 18,034
  • 5
  • 46
  • 57
0

The size of the string is too long, check this question

Community
  • 1
  • 1
Carlos Valenzuela
  • 816
  • 1
  • 7
  • 19
0

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.

Reboot
  • 1,716
  • 2
  • 14
  • 27
  • Two's complement is not the same as "one digit for sign", because if it were, there would be a positive and a negative zero. – Joachim Sauer Jan 11 '11 at 16:25
  • I did not write that it is a sign bit, only that it is used to distinguish between positive and negative numbers. There is really no need to explain how the Two's complement works in the answer, in my opinion. – Reboot Jan 11 '11 at 16:29