0

Ive written a program for converting binary to decimal, however I was wondering how can I do it without using Math.pow ( ) and by only using methods charAt ( ) and length()

thank you,, any help would be appreciated

public class BinaryToDecimal{

    public static void main(String[] args){
        String binaryString = args[0];
        int decimalValue;

        int length = binaryString.length();
        double j = 0;

        for (int i=0; i< binaryString.length(); i++){
            if (binaryString.charAt(i)== '1'){
                j = j+  Math.pow(2, binaryString.length() - 1 - i);
            }
        }

        decimalValue = (int) j;   

        System.out.println(decimalValue);
    }
}
initramfs
  • 8,275
  • 2
  • 36
  • 58

2 Answers2

1

You can try this:

int j = 0;
for (int i=0; i< binaryString.length(); i++)
{
  j <<= 1;
  if (binaryString.charAt(i)== '1')
  {
    ++j;
  }
}
Jim Rhodes
  • 5,021
  • 4
  • 25
  • 38
0

Yes, you can (and should) do the conversions without using Math.pow.

The following code adds the nth power of 2 to j:

j += 1 << n;

But I recommend the answer by Jim Rhodes, because it is a simpler solution. You do not need to raise 2 to various powers; all you really need to know is that every time you write an extra digit on the right-hand end of a binary number, the value of the previous digits is doubled. For example, 111 in binary equals the decimal number 7, but if I write one more digit, like so, 1110, then the value becomes equal to 2*7, that is, 14 in decimal notation.

David K
  • 3,147
  • 2
  • 13
  • 19