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

前端 未结 9 1375
野性不改
野性不改 2020-11-27 14:30

I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:

bi         


        
9条回答
  •  时光说笑
    2020-11-27 15:29

    static int binaryToInt (String binary){
        char []cA = binary.toCharArray();
        int result = 0;
        for (int i = cA.length-1;i>=0;i--){
            //111 , length = 3, i = 2, 2^(3-3) + 2^(3-2)
            //                    0           1  
            if(cA[i]=='1') result+=Math.pow(2, cA.length-i-1);
        }
        return result;
    }
    

提交回复
热议问题