I was trying to run the following line of code:
System.out.println("11111111111111111111111111111111 is " + Integer.parseInt("11111111111111111111111111111111", 2));
and the result is:
java.lang.NumberFormatException: For input string: "11111111111111111111111111111111"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
I expected it to parse that string into -1, because when I do the following:
System.out.println(-1 + " is " + Integer.toBinaryString(-1));
I get the output:
-1 is 11111111111111111111111111111111
What is going on here?
Integer.toBinaryString
treats the int
value as an unsigned integer, as per the documentation:
Returns a string representation of the integer argument as an unsigned integer in base 2.
The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.
... whereas Integer.parseInt
assumes that if you want a negative number, you'll have a negative sign at the start. In other words, the two operations aren't just the reverse of each other.
Now you could get what you want by parsing it as a long
(with Long.parseLong(text, 2)
and then casting the result back to int
. That works as you can represent 232-1 as a long
, and when you cast it to int
you'll get -1.
See more on this question at Stackoverflow