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;
      }
}

Look at how to do it, you have the detailed algorithm here: https://javarevisited.blogspot.com/2015/01/how-to-convert-binary-number-to-decimal.html

The algorithm implementation suggested there takes an int as input. Here is the String verion:

public static int binaryToDecimal(String binary) {
     int decimal = 0;
     int power = 0;
     int currentIndex = binary.length() - 1;

     while (currentIndex>=0) {
         int currentDigit = binary.charAt(currentIndex) - '0';  //char to number conversion
         decimal += currentDigit * Math.pow(2, power);
         power++;
         currentIndex--;
     }
     return decimal;
 }

The char to number conversion is needed because we need to convert the chars '1' or '0' to the number 1 or 0. We can do this using the ascii code of the chars ('0'=48 and '1'=49)


// 1. In the first method we will use parseInt() function to convert binary to decimal..
    
    let binaryDigit = 11011; let getDecimal = parseInt(binaryDigit, 2);
    console.log(getDecimal);
    

// 2. In the second method we going through step by step, using this trick we can improve our logic better..
    
    let binaryDigit = 11011; let splitBinaryDigits =
    String(binaryDigit).split(""); let revBinaryArr =
    splitBinaryDigits.reverse(); let getDecimal = 0;
    
    revBinaryArr.forEach((value, index) => {  

     let getPower = Math.pow(2, index); 
        getDecimal += value * getPower; 

});
    console.log(getDecimal);