Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: convert binary string to int

I'm trying to convert a couple of binary strings back to int. However it doesn't convert all my binary strings, leaving me a java.lang.NumberFormatException exception. Here is my test code with 3 binary string:

public class Bin {

    public static void main(String argvs[]) {
            String binaryString ;
            binaryString = Integer.toBinaryString(~0);
            //binaryString = Integer.toBinaryString(~1);
            //binaryString = "1010" ;
            int base = 2;
            int decimal = Integer.parseInt(binaryString, base);
            System.out.println("INPUT=" + binaryString + " decimal=" + decimal) ;
    }
}

If I convert the "1010" it works great, but when I try to convert one of the other two I get the exception. Can someone explain to me why this is ?

Cheers

like image 228
Jeanluca Scaljeri Avatar asked Feb 14 '13 20:02

Jeanluca Scaljeri


2 Answers

From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString(int) : the toBinaryString() method converts its input into the binary representation of the "unsigned integer value is the argument plus 232 if the argument is negative".

From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) : the parseInt() method throws NumberFormatException if "The value represented by the string is not a value of type int".

Note that both ~0 and ~1 are negative (-1 and -2 respectively), so will be converted to the binary representations of 232-1 and 232-2 respectively, neither of which can be represented in a value of type int, so causing the NumberFormatException that you are seeing.

like image 148
David Conneely Avatar answered Oct 15 '22 21:10

David Conneely


As explained above, Integer.toBinaryString() converts ~0 and ~1 to unsigned int so they will exceed Integer.MAX_VALUE.

You could use long to parse and convert back to int as below.

int base = 2;
for (Integer num : new Integer[] {~0, ~1}) {
    String binaryString = Integer.toBinaryString(num);            
    Long decimal = Long.parseLong(binaryString, base);
    System.out.println("INPUT=" + binaryString + " decimal=" + decimal.intValue()) ;
}
like image 45
Eddie Avatar answered Oct 15 '22 20:10

Eddie