NumberFormatExceprion for binary string

62 Views Asked by At

I'm trying to get int from String "11010001110011000000000111111110" with code:

int n = Integer.parseInt("11010001110011000000000111111110", 2);

but i get an error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "11010001110011000000000111111110"
1

There are 1 best solutions below

0
On BEST ANSWER

It is simply because the value represented by the string with binary content is too large for an int data type. You need to parse to long data type. The binary string represents a value of 3519807998. Integer maximum value (Integer.MAX_VALUE) is: 2147483647. Try this:

String binaryString = "11010001110011000000000111111110";
long n = Long.parseLong(binaryString, 2);

Or this way:

String binaryString = "11010001110011000000000111111110";
long lng = new BigInteger(binaryString, 2).longValue();
System.out.println(lng);