0

The binary string is "10101010101010101010101010101010", 32 bits

Got this exception when i try

Integer.parseInt("10101010101010101010101010101010", 2);

But the same string(add "0b" prefix)

System.out.print(0b10101010101010101010101010101010);

return -1431655766.

Is this a valid binary string?

3 Answers3

2

Integer.parseInt() is the wrong method as it only accepts signed numbers.

With Java8, use:

Integer.parseUnsignedInt("10101010101010101010101010101010", 2);

Before Java8, use:

(int) Long.parseLong("10101010101010101010101010101010", 2);
Ralf Kleberhoff
  • 6,990
  • 1
  • 13
  • 7
1

The value you wanted to convert goes beyond the int type size, UseBigInteger:

        BigInteger b = new BigInteger("10101010101010101010101010101010",2);
Mustapha Belmokhtar
  • 1,231
  • 8
  • 21
1
Integer.parseInt("10101010101010101010101010101010", 2);

Note that this would be 2863311530, which would cause an overflow, as it is above Integer.MAX_VALUE.

System.out.print(0b10101010101010101010101010101010);

This however uses the internal representation of an integer, which is two-complement form. Thats why it is negative. The Integer.parseInt() however treats it as an unsigned binary number, which causes the Exception.

It is important to understand the different bit representations.

Edit: If you want your input to be interpreted as two-complement, use this:

Integer.parseUnsignedInt("10101010101010101010101010101010", 2);
Dorian Gray
  • 2,913
  • 1
  • 9
  • 25