NumberFormatExceprion for binary string

Dmitry Kuznetsov :

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"
DevilsHnd :

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); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=296033&siteId=1