2

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;
      }
}
3
  • Why do you have to write your own method instead of using those in jdk? Commented Oct 9, 2018 at 9:51
  • just what i was told to do in my university Commented Oct 9, 2018 at 10:41
  • An int is not a decimal number. It just gets displayed in decimal format by default when you print it. You can also print it in binary, octal and hexadecimal formats. Intrinsically, an int is neither decimal nor hex. Its appearance is only what you choose to print it as. Commented Oct 9, 2018 at 13:55

5 Answers 5

2

// 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);

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

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

Comments

0

Not sure if you had to do it manually by your teacher, but if not there are some available builtin you can use:

// Convert binary String to integer:
// TODO: Surround with try-catch
int outputInt = Integer.parseInt(inputBinaryString, 2);

// Convert integer to binary String:
String outputBinaryString = Integer.toBinaryString(inputInt);

// Pad leading zeros to make the length 8:
String paddedResult = String.format("%8s", outputBinaryString).replace(' ', '0');

Try it online.

Comments

-1

Try this code

import java.util.Scanner;

class BinaryToDecimal
{
        public static void main(String args[])
        {
            Scanner s=new Scanner(System.in);

            System.out.println("Enter a binary number:");
            int n=s.nextInt();

            int decimal=0,p=0;

            while(n!=0)
            {
                decimal+=((n%10)*Math.pow(2,p));
                n=n/10;
                p++;
            }

            System.out.println(decimal);
        }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.