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

前端 未结 9 1234
野性不改
野性不改 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.

    0 讨论(0)
  • 2020-11-27 15:33

    If you're worried about performance, Integer.parseInt() and Math.pow() are too expensive. You can use bit manipulation to do the same thing twice as fast (based on my experience):

    final int num = 87;
    String biStr = Integer.toBinaryString(num);
    
    System.out.println(" Input Number: " + num + " toBinary "+ biStr);
    int dec = binaryStringToDecimal(biStr);
    System.out.println("Output Number: " + dec + " toBinary "+Integer.toBinaryString(dec));
    

    Where

    int binaryStringToDecimal(String biString){
      int n = biString.length();      
      int decimal = 0;
      for (int d = 0; d < n; d++){
        // append a bit=0 (i.e. shift left) 
        decimal = decimal << 1;
    
        // if biStr[d] is 1, flip last added bit=0 to 1 
        if (biString.charAt(d) == '1'){
          decimal = decimal | 1; // e.g. dec = 110 | (00)1 = 111
        }
      }
      return decimal;
    }
    

    Output:

     Input Number: 87 toBinary 1010111
    Output Number: 87 toBinary 1010111
    
    0 讨论(0)
  • 2020-11-27 15:34

    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;
    }
    
    0 讨论(0)
提交回复
热议问题