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

前端 未结 9 1333
野性不改
野性不改 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:33

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

    I guess I'm even more bored! Modified Hassan's answer to function correctly.

提交回复
热议问题