Skip to content
Advertisement

change binary to decimal

I have to write a method that changes binary to decimal. Write a method that will convert the supplied binary digit (as a string) to a decimal number.

  • convertToDecimal(“01101011”) = 107
  • convertToDecimal(“00001011”) = 11

i have created it to change decimal to binary however im not sure how to create it binary to decimal.

public String convertToBinary(int decimal) {

    int n = decimal;
    int digit;
    String out = "";
    while (n > 0){
     n = decimal/2;
     digit = decimal % 2;
     out = digit + out;
     decimal = n;
    }

    out = addPadding(out);
    return out;
    }

private String addPadding(String s){
      String out = s;
      int len = s.length();
      if (len == 8) return s;
      else{
          switch(len){
            case 7:
                out = "0"+s;
                break;
            case 6:
                out = "00"+s;
                break;
            case 5:
                out = "000"+s;
                break;
           }
       }
       return out;
      }
}

Advertisement

Answer

1. We have to traverse from backwards as we do in the binary to decimal conversion.
2. If the character is '1', then we will add the value of power of 2.

public static int binaryToDecimal(String binary) {
        int value = 0,power = 0;
        for(int i = binary.length() - 1; i >= 0;i--) {
            if(binary.charAt(i) == '1') {
                value += Math.pow(2, power);
            }
            power++;
        }
        return value;
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement