0

I am having trouble getting this method, which converts an integer from binary to decimal, to work properly. The main problem I have found is that with binary numbers that end in 0, the last 0 is ignored by the program. For example, if I input 1010, the program would return 5 instead of 10. Below is my method for this conversion.

public int toDecimal(int inBase2){
    int num = 0;
    if(inBase2 < 0){
      num = -1;
      return num;
    }
    if(inBase2 == 0 && num == 0){
      return num;
    }else{
      num = inBase2 % 10 * (int)(Math.pow(2, Math.log10(inBase2)));
    return num + toDecimal(inBase2 / 10);
    }
  }

How would I go about fixing the program in a way that allows it to read the final 0 in the binary integer correctly?

1 Answer 1

1

You're doing the calculation the wrong way round. The least significant digit in the binary number is treated as though it's the most significant. So effectively, 1010 returns the result for 0101. Right now, the first digit you process, in the ones place, is multiplied by Math.pow(2, Math.log10(inBase2)), and given the most weight. Instead, you should multiply the results of the recursive function, so later calls (which represent higher value digits) are multiplied more. Example

public int toDecimal(int inBase2){
    int num = 0;
    if(inBase2 < 0){
        num = -1;
        return num;
    }
    if(inBase2 == 0 && num == 0){
        return num;
    }else{
        num = inBase2 % 10;
        return num + 2 * toDecimal(inBase2 / 10);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!!! <3 This completely opened my eyes to what I was doing wrong. I didn't realize that I had been doing the calculations the wrong way around. It makes so much more sense now!

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.