1
\$\begingroup\$

I just recently began going over number systems again, granted I didn't pay very much attention to it the first time for lack of understanding its importance (I've only been coding for a year and some change). Below this paragraph of text I have a simple Binary to Decimal converter, and I was wondering if there's a better way to do this, or if my algorithm is okay:

import java.util.Scanner;

public class BinaryToDecimal {

public static void main(String[] args) {
    Scanner scan1 = new Scanner(System.in);
    System.out.println("Enter a binary number: ");
    String Binary = scan1.next(); // 11011
    double power = 0;
    double sum = 0;

    for (int i = Binary.length() - 1; i >= 0; i--) {
        char TempHold = Binary.charAt(i);
        double num = Character.getNumericValue(TempHold);
        sum = (sum + (num * (Math.pow(2, power))));
        power++;
    }


    System.out.println(sum + "(10)");

}

}

My process:

  1. The first step was to, of course, allow the user to input their own binary number for testing purposes with a scanner and a variable of String called Binary for the initialization of this input (I chose to make this a String vs an Integer for looping purposes).
  2. Next I created a variable of type double called power that will start off at 0 and be utilized in the for loop later.

  3. Lastly, as far as preliminary variable declarations go, I created a sum variable to hold the sum of the binary-decimal conversion.

  4. Within the for loop I ensured that my iterator traversed the String backwards in respect to my method of conversion.

  5. After setting up the for loop, I created a variable of type Character called TempHold to seize and store the character of the Binary variable that corresponds to the current iteration of the loop.

  6. My next step was to parse the TempHold Character variable into a String so that I could utilize it arithmetically in my conversion method.

  7. At the end of this for loop I incremented the power variable so that I could increase the value of the exponent being used in the conversion method.

\$\endgroup\$
1
  • \$\begingroup\$ While your code is a nice example for learning the principles and received a nice review by Ralf, do not forget that the java base library contains solutions for most everyday problems. In this case, have a look at Integer.parseInt(String s, int radix) for parsing and Integer.toBinaryString(int i) for output. \$\endgroup\$
    – mtj
    Commented Jan 14, 2019 at 7:03

1 Answer 1

0
\$\begingroup\$

Your algorithm is ok, there are only a few minor hints for improvement:

You're using double-typed variables. Although in your case the computations will be exact up to fairly large numbers, it's generally safer to use int or long if you don't need the fractional part.

Two of your variable names begin with an upper-case letter (Binary and TempHold). That's unusual for Java code, as the vast majority of programs follows the naming conventions, so much that I find it irritating to read non-conforming code.

Your variable power has a name that confused me first. I'd call it exponent (in mathematics, "power" is the result of exponentiation). And I'd rename TempHold to digitChar and num to digitVal.

Math.pow() isn't really fast, so I recommend a different approach. With every iteration, the power grows by a factor of two, so I'd use something like power = power * 2; inside the loop.

For production code, you should separate input/output from computation, e.g. by putting the conversion part into a method of its own.

It's good style to close Scanners when they are finished (although that will eventually be done by Java's garbage collector if you don't do it explicitly).

So, my version of your program would be:

import java.util.Scanner;

public class BinaryToDecimal {

    public static void main(String[] args) {
        Scanner scan1 = new Scanner(System.in);
        System.out.println("Enter a binary number: ");
        String binary = scan1.next(); // 11011

        String decimal = toDecimal(binary);

        System.out.println(decimal + "(10)");
        scan1.close();
    }

    public static String toDecimal(String binary) {
        long power = 1;
        long sum = 0;

        for (int i = binary.length() - 1; i >= 0; i--) {
            char digitChar = binary.charAt(i);
            int digitVal = Character.getNumericValue(digitChar);
            sum = sum + digitVal * power;
            power = power * 2;
        }
        return String.valueOf(sum);
    }
}
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.