Results 1 to 2 of 2
  1. #1
    cachi is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default 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.

    Java 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.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    10

    Default

    We only want to add the values of the bits that are turned on
    and to ignore the zero/off bits.
    Java 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;
    }

Similar Threads

  1. round to two decimal places
    By javaMike in forum New To Java
    Replies: 3
    Last Post: 12-24-2011, 03:01 AM
  2. rounding double to two decimal places
    By javaMike in forum Advanced Java
    Replies: 15
    Last Post: 03-10-2010, 01:04 AM
  3. Java calculator decimal
    By cart1443 in forum New To Java
    Replies: 2
    Last Post: 04-16-2008, 01:19 PM
  4. Capping decimal places
    By Rageagainst20 in forum New To Java
    Replies: 1
    Last Post: 12-20-2007, 10:28 PM
  5. Converts from Fahrenheit to Celsius
    By trill in forum New To Java
    Replies: 1
    Last Post: 08-06-2007, 05:52 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •