Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

parseint

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.

like image 420
Codebender Avatar asked Nov 19 '25 14:11

Codebender


2 Answers

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

System.out.println(Integer.parseUnsignedInt(Integer.toBinaryString(-1), 2));
like image 125
Tagir Valeev Avatar answered Nov 22 '25 02:11

Tagir Valeev


Try using

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

Using:

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

Output:

-1
like image 22
M. Shaw Avatar answered Nov 22 '25 02:11

M. Shaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!