Reputation: 173
I am working on a program where I am trying to take a binary string and convert it to an integer using this piece of code:
int x = Integer.parseInt(arrayList.get(count), 2);
//arrayList is a collection of 30 character binary strings
//count is an incrementing integer used to choose which string to use while inside of a while loop
I have tested this program with strings such as "001010", however with larger strings such as "100000110000010100001111010110" compiles, but terminal output gives me an error:
"@ java.lang.NumberFormatException.forInputString(NumberFormatException.java:(line number))
How can I fix this?
Upvotes: 2
Views: 130
Reputation: 17592
You can try java.math.BigInteger
.
String bin = "100000110000010100001111010110";
BigInteger bi = new BigInteger(bin, 2);
System.out.println(bi);
Output:
549536726
You can also do it using Long.valueOf()
. However, with Long your binary strings can be up to 63 bits long, whereas with BigInteger the length can be of arbitrarily many bits.
String bin = "100000110000010100001111010110";
long biLong = Long.valueOf(bin, 2);
System.out.println(biLong);
Upvotes: 1