# Converts a binary number to a decimal

• 08-01-2007, 06:14 AM
cachi
Converts a binary number to a decimal
I need to write a method that converts a binary number to a decimal. Here is what i have so far any suggestions on how i can get this to work right now it returns 147.0 when you enter the binary number 11 which should have the decimal equivalent of 3.

Does anyone know where i messed up? I've been working on just this method for probably 8 hours including yesterday and today and i don't think I'm even close.

Code:

```static double toDecimal (String s)   {     int l = s.length();     double result = 0;     for (int i = 0; i < l; i++)     {       result = result + s.charAt(i) * Math.pow(2, (s.length() - i - 1));     }     return result;   }```
Thanks.
• 08-01-2007, 09:57 AM
hardwired
We only want to add the values of the bits that are turned on
and to ignore the zero/off bits.
Code:

```private static double toDecimal(String s) {     int l = s.length();     double result = 0;     for (int i = 0; i < l; i++) {         if(s.charAt(i) == '1')             result = result + Math.pow(2, (s.length() - i - 1));     }     return result; }```