binary to decimal

This is a discussion on binary to decimal within the C Programming forums, part of the General Programming Boards category; ok I have an array with 8 characters composed of either 0s or 1s. for example i have an array ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    20

    binary to decimal

    ok I have an array with 8 characters composed of either 0s or 1s. for example i have an array that if you print all its contents, you will get 01110100. however the characters are assigned randomly, so the next time i run the program the array may contain 11010110

    even though they are just characters they are supposed to represent a binary digit. how can I convert the binary representation into a decimal number?

    so for example say the array contains 10000011, how can I convert that to 259?

    i know how to convert it on paper by the way.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Do you mean you have something like char binary[8]? Where each char is either '1' or '0'? Then take what you have on paper and type it into your program, remembering that the first digit is binary[0] and the last is binary[7].

  3. #3
    Registered User valaris's Avatar
    Join Date
    Jun 2008
    Location
    RING 0
    Posts
    507
    binary[0] x 2 ^ 0 + binary[0] x 2 ^ 1 and so on through all your numbers. This works for any base if you exchange the 2 for the base...for converting to base 10 that is.
    example:
    1010101
    (1 * 2 ^ 0) + (0 * 2 ^ 1) + (1 * 2 ^ 2) + (0 * 2 ^ 3) + (1 * 2 ^ 4) + (0 * 2 ^ 5) + (1 * 2 ^ 6)
    85<===

  4. #4
    Registered User
    Join Date
    Jul 2008
    Posts
    20
    word i got it working

    edit: thanks valaris, i did it a different way but thanks for your time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need help with decimal to binary Algorithm
    By webznz in forum C Programming
    Replies: 4
    Last Post: 03-13-2008, 03:52 AM
  2. Confused by expression.
    By Hulag in forum C Programming
    Replies: 3
    Last Post: 04-07-2005, 07:52 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. binary to decimal
    By miryellis in forum C Programming
    Replies: 7
    Last Post: 03-14-2004, 07:35 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21