Thread: Binary to integer

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    8

    Binary to integer

    "Hello

    I have a long binary string in a char array like this

    char abc [] = "100000001010000000110010";

    I need to convert this string to a long long.
    I can't use atoi to convert it to long long using atoll because this string is more than 10 (11 including null termination) characters long. And starts giving me junk values.

    Once I convert it to an integer I will run a program / function to convert the long long number to its equivalent radix 10 format..

    Does anyone have any suggestions how I can go about this? or some other way to approach this problem
    Thanks in advance...

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Use a loop. Starting at the right end of the array, the value my be computed by multiplying each digit (0 or 1) by an appropriate power of 2, and adding up.

    longlongvalue = 0*1 + 1*2 + 0*4 + 0*8 + 1*16 + 1*32 ..... <until beginning of array>.

    where the digits I've coloured in red are the the digits, working backward from the end of the end of the array.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    If your compiler has 64 bit ints... it should also have an strtoull() function... which is part of the C99 standard...
    Code:
    unsigned long long abcnum
    
    abcnum = strtoull(abc,NULL,2);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Convert Binary Number into Integer
    By darres90 in forum C++ Programming
    Replies: 1
    Last Post: 04-14-2011, 11:05 AM
  2. Long integer to binary pattern
    By mark522 in forum C Programming
    Replies: 3
    Last Post: 12-17-2009, 06:03 AM
  3. integer to binary
    By rs07 in forum C Programming
    Replies: 2
    Last Post: 09-17-2008, 12:18 AM
  4. How to display integer to binary format?
    By franziss in forum C++ Programming
    Replies: 3
    Last Post: 09-21-2005, 11:32 PM
  5. Recursive function that changes an integer to binary
    By advocation in forum C++ Programming
    Replies: 6
    Last Post: 04-10-2005, 07:08 PM