Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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);
}
like image 431
kungfoo Avatar asked Jan 11 '11 16:01

kungfoo


3 Answers

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

like image 107
Omnifarious Avatar answered Nov 09 '22 21:11

Omnifarious


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.

like image 44
jjnguy Avatar answered Nov 09 '22 20:11

jjnguy


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

like image 23
Evgeniy Dorofeev Avatar answered Nov 09 '22 20:11

Evgeniy Dorofeev