0

I want to convert Integer.MAX_VALUE to binary and want the represenation to be of type int. I passed it to Integer.tobinarystring() and wraped that with Integer.parseint but i get numberformatexception.

Here is the code

System.out.println(
    Integer.parseInt(
            Integer.toBinaryString(Integer.MAX_VALUE)
    )
);

Here is the exception

Exception in thread "main" java.lang.NumberFormatException: For input string: "1111111111111111111111111111111"
elbraulio
  • 994
  • 6
  • 15
proger
  • 45
  • 7

2 Answers2

4

Integer.MAX_VALUE is 2,147,483,647

In binary this is: 1111111111111111111111111111111

If we treat that like an integer again, which is 1,111,111,111,111,111,111,111,111,111,111 you can probably see that it is much larger than the max value.

You probably want to look into BigInteger if you really need to deal with that as a int.

zzevannn
  • 3,414
  • 2
  • 12
  • 20
  • Ok that make sense thank alot! I will look into it but do you know why i have not gotten the "literal out of range" error since this is the case? – proger Jan 14 '19 at 20:51
  • I actually want to print groups of 8 bits and want it to be int so i can format it with decimalformat rather than having to do a for loop for a string – proger Jan 14 '19 at 20:55
2

If you want to get the integer value of the binary string

1111111111111111111111111111111

you must use another signature of parseInt() that takes as 2nd parameter the radix,
in this case of a binary string the radix is 2

String str = Integer.toBinaryString(Integer.MAX_VALUE);
int number = Integer.parseInt(str, 2);
System.out.println(number);

it will print:

2147483647
forpas
  • 160,666
  • 10
  • 38
  • 76