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?
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.
Since Java 8 you can use Integer.parseUnsignedInt(s, 2);:
System.out.println(Integer.parseUnsignedInt(Integer.toBinaryString(-1), 2));
Try using
int i = Long.valueOf(str, 2).intValue();
Using:
int i = Long.valueOf("11111111111111111111111111111111", 2).intValue();
System.out.print(i);
Output:
-1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With