3

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.

Community
  • 1
  • 1
Codebender
  • 14,221
  • 7
  • 48
  • 85
  • "This wont work in all cases" ... can you give an example of a case where it won't work? – ajb Aug 18 '15 at 04:36
  • 1
    Your question was about `int` or `Integer` types, so it was far from clear that "all cases" was referring to larger types. And it certainly _does_ work in "all cases" that are covered by your parenthesized phrase. – ajb Aug 18 '15 at 04:39

4 Answers4

4

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

System.out.println(Integer.parseUnsignedInt(Integer.toBinaryString(-1), 2));
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
3

Try using

int i = Long.valueOf(str, 2).intValue();

Using:

int i = Long.valueOf("11111111111111111111111111111111", 2).intValue();
System.out.print(i);

Output:

-1
M. Shaw
  • 1,742
  • 11
  • 15
0

According to the Integer API, Integer.toBinaryString() returns the twos complement, not the signed version. This is why this throws a NumberFormatException. You can use Integer.parseUnsignedInt() instead.

saagarjha
  • 2,221
  • 1
  • 20
  • 37
0

"11111111111111111111111111111111" too long

System.out.println(Integer.toBinaryString(-1)); 
// This output's "11111111111111111111111111111111"
System.out.println(Long.parseLong(Integer.toBinaryString(-1), 2));
lie
  • 11