4

I want to convert binary string to dec.

public class HelloWorld{

     public static void main(String []args){

        System.out.println(Integer.parseInt("000011011111110111000001110000111110", 2));
     }
}

I get error:

java.lang.NumberFormatException: For input string: "000011011111110111000001110000111110".

How to fix it?

cahen
  • 15,807
  • 13
  • 47
  • 78
phnmnn
  • 12,813
  • 11
  • 47
  • 64

3 Answers3

3

Short solution - Integers simply don't go that high. That's not an int.

ParseInt() documentation mentions, you recieve a string and a radix, and get back the result of the convertion. However, integers are 4 bytes = 32 bits, and thus range from -(2^31) to 2^31-1, and your number - 11011111110111000001110000111110, is in fact 32 bits long - which means, it's bigger than the maximal value. Thus, the function throws this NumberFormatException - this is not a valid value for an int.

If you'd like to fix it, I'd use a ByteBuffer, like described here:

ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN);  // if you want little-endian
int result = buffer.getShort(); // use with a bigInteger instead. you could use any of the bytebuffer functions described in the link :)
Community
  • 1
  • 1
A. Abramov
  • 1,823
  • 17
  • 45
2

You can use BigInteger class and store the number as long:

BigInteger bigInt=new BigInteger("000011011111110111000001110000111110");
long a=bigInt.longValue();

The value you are going to store is too big for int and does not fall inside the range the type int can hold(-(2^31) to 2^31-1).So it throws NumberFormatException.long is a suitable option here.

hermit
  • 1,048
  • 1
  • 6
  • 16
0

You can use Long.parseLong for the string in your question, still you may find a limit in that also, so you have to implement different logic.

You can have a method that convert the binary string to integer.

public static long binaryToInteger(String binaryString) {
    char[] chars = binaryString.toCharArray();
    long resultInt = 0;
    int placeHolder = 0;
    for (int i=chars.length-1; i>=0; i--) {
        if (chars[i]=='1') {
          resultInt += Math.pow(2,placeHolder);
        }
        placeHolder++;
    }
    return resultInt;
}
seenukarthi
  • 8,241
  • 10
  • 47
  • 68
  • `Math.pow(2, placeHolder)` can return wrong value since it returns `double` and you're casting it to `int`. It's better to use `1 << placeholder`. http://stackoverflow.com/questions/10416694/java-results-differ-for-intmath-pow2-x-and-1x – egor.zhdan Aug 16 '15 at 09:54
  • This is most efficient: 'long r=0; for (int i=0; i – krzydyn Aug 16 '15 at 10:04