How to convert a Binary String to a base 10 integer in Java How to convert a Binary String to a base 10 integer in Java java java

How to convert a Binary String to a base 10 integer in Java


You need to specify the radix. There's an overload of Integer#parseInt() which allows you to.

int foo = Integer.parseInt("1001", 2);


This might work:

public int binaryToInteger(String binary) {    char[] numbers = binary.toCharArray();    int result = 0;    for(int i=numbers.length - 1; i>=0; i--)        if(numbers[i]=='1')            result += Math.pow(2, (numbers.length-i - 1));    return result;}


int foo = Integer.parseInt("1001", 2);

works just fine if you are dealing with positive numbers but if you need to deal with signed numbers you may need to sign extend your string then convert to an Int

public class bit_fun {    public static void main(String[] args) {        int x= (int)Long.parseLong("FFFFFFFF", 16);        System.out.println("x =" +x);               System.out.println(signExtend("1"));        x= (int)Long.parseLong(signExtend("1"), 2);        System.out.println("x =" +x);        System.out.println(signExtend("0"));        x= (int)Long.parseLong(signExtend("0"), 2);        System.out.println("x =" +x);        System.out.println(signExtend("1000"));        x= (int)Long.parseLong(signExtend("1000"), 2);        System.out.println("x =" +x);        System.out.println(signExtend("01000"));        x= (int)Long.parseLong(signExtend("01000"), 2);        System.out.println("x =" +x);    }    private static String signExtend(String str){        //TODO add bounds checking        int n=32-str.length();        char[] sign_ext = new char[n];        Arrays.fill(sign_ext, str.charAt(0));        return new String(sign_ext)+str;    }}output:x =-111111111111111111111111111111111x =-100000000000000000000000000000000x =011111111111111111111111111111000x =-800000000000000000000000000001000x =8 

I hope that helps!