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:
- 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).
Next I created a variable of type double called power that will start off at 0 and be utilized in the for loop later.
Lastly, as far as preliminary variable declarations go, I created a sum variable to hold the sum of the binary-decimal conversion.
Within the for loop I ensured that my iterator traversed the String backwards in respect to my method of conversion.
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.
My next step was to parse the TempHold Character variable into a String so that I could utilize it arithmetically in my conversion method.
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.
Integer.parseInt(String s, int radix)
for parsing andInteger.toBinaryString(int i)
for output. \$\endgroup\$