Search code examples
javaparseint

Integer.parseInt(x, 2) is not considering sign bit


When doing Integer.parseInt(x, 2), it's not considering the sign bit.

Take this example,

System.out.println(Integer.toBinaryString(-1)); // This output's "11111111111111111111111111111111"
System.out.println(Integer.parseInt(Integer.toBinaryString(-1), 2));

The second line throws,

Exception in thread "main" java.lang.NumberFormatException: For input string: "11111111111111111111111111111111"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at com.Test.main(Test.java:116)

I have a scenario to convert Integer to Binary String and then convert it back.

Is there a way to let the parseInt() method parse it with the sign bit?

EDIT:

The answer's in this question have a hacky solution to use parseXX() method on a larger datatype (eg: Integer.parseInt() while needing short, or Long while needing int). This wont work if someone is trying to parse a negative long (since there's no larger type than long).

But @Tagir's answer seems to work for all Types. So leaving this question open.


Solution

  • Since Java 8 you can use Integer.parseUnsignedInt(s, 2);:

    System.out.println(Integer.parseUnsignedInt(Integer.toBinaryString(-1), 2));