2

I'm looking to create a simple program that will convert binary numbers to decimal numbers, without using math.pow(). Here's what I have so far, using Math.pow at the end:

import java.util.Scanner;
public class  Question1 {
  public static void main(String[] args) {
    System.out.println("Enter a binary number");
    Scanner inputKeyboard = new Scanner(System.in);
    String binaryNumber = inputKeyboard.nextLine();
    while (!checkIfBinary(binaryNumber)) {
      System.out.println("That is not a binary number.  Enter a binary number");
      binaryNumber = inputKeyboard.nextLine();
    }
    int decimalNumber = binaryToNumber(binaryNumber);
    System.out.println("Your number in base 10 is " + decimalNumber + ".");
  }

  public static boolean checkIfBinary(String input) {
    for (int i = 0; i < input.length(); i++) {
      if(input.charAt(i) != '0' && input.charAt(i) != '1') {
        return false;
      }
    }
    return true;
  }

  public static int binaryToNumber(String numberInput) {
    int total = 0;
    for (int i = 0; i < numberInput.length(); i++) {
      if (numberInput.charAt(i) == '1')  {
        total += (int) Math.pow(2, numberInput.length() - 1 - i);
      }
    }
    return total;
  }
}

I'm encountering a problem doing the exponentiation without math.pow. I know I need to use a loop, and this loop should multiply 2 by itself numberInput.length() - 1 - i times. But I'm having difficulty implementing this.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Hint: You can multiply the total by two and add or not add 1 depending on the next digit, which will give you the new total after one more binary digit. – laune Feb 03 '15 at 19:44
  • 1
    Uh, you're not converting binary to "decimal". You're converting binary to the Java internal numeric form -- `int` -- and that just happens to be binary. – Hot Licks Feb 03 '15 at 19:44
  • Isn't this line wrong, shouldn't it be " || " instead of &&, if(input.charAt(i) != '0' && input.charAt(i) != '1') – Johan Feb 03 '15 at 19:46
  • You don't need an exponentiation to convert binary number to decimal. I think something like `Integer.parseInt(YourBinaryIntNumber, 2)` does exactly what you need. – Everv0id Feb 03 '15 at 19:48
  • @jdhw, please read my updated answer. – Sufiyan Ghori Feb 03 '15 at 21:55
  • @SufihanGhori, I appreciate your help but unfortunately in this intro java course, the problem specifies that we only need use "the nextLine method, loops, the length(), charAt(int index) and equals(String other) methods of Strings" for this question. –  Feb 03 '15 at 22:08
  • @Johan, when I use || it doesn't recognize any binary number entered. –  Feb 03 '15 at 22:12
  • Ok but does the checkbinary method work with && ? – Johan Feb 03 '15 at 22:37

4 Answers4

3

parse your String to integer and provide it the base 2

int decimalValue = Integer.parseInt(yourStringOfBinary, 2);

but keep in mind that the max value of an Integer is 2^31-1 Which in binary is:

1111111111111111111111111111111

therefore, you will get java.lang.NumberFormatException error if you input bigger binary value than above, to solve this issue, use BigInteger,

int decimalValue = new BigInteger(yourBinaryString, 2).intValue()
Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
2

Integer let you do this by specifying the base of the entered number :

Integer.parseInt("101101101010111", 2); 

This does not use Math.pow :)

This is maybe not what you wanted, but anyway might help anyone.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
1

I'd work backwards from the end of the string and just calculate the power for each character incrementally:

public static int binaryToNumber (String numberInput) {
    int currentPower = 1;
    int total = 0;

    for (int i = numberInput.length() - 1; i >= 0; i--) {
        if (numberInput.charAt(i) == '1')  {
            total += currentPower;
        }
        currentPower *= 2;
    }

    return total;
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

You can use Integer.parseInt.

Similar question has been answered here:

How to convert binary string value to decimal

Only difference is that in the answer referenced above, they are converting a String ("01101") into a decimal integer.

Also reference the Javadoc Integer.parseInt.

Community
  • 1
  • 1
user1521213
  • 139
  • 1
  • 6