Search code examples
cstringtype-conversionatoi

Using atoi() in C to parse character array with binary values


I'm trying to convert a string of binary characters to an integer value.

For example: "100101101001" I would split it into four segments using a for loop then store it in array[4]. However whenever I use the function atoi(), I encounter a problem where it does not convert the character string properly if the string starts with "0".

An example would be "1001" = 1001, but if it is 0110 it would be converted to 110, also with 0001 it would be come only 1.

Here is the code that I made:

for(i = 0; i < strlen(store); i++)
{
    bits[counter] = store [i];
    counter++;
    if(counter == 4)
    {   
        sscanf(bits, "%d", &testing);
        printf("%d\n", testing);
        counter = 0;
    }       
}

Solution

  • The atoi() function only converts decimal numbers, in base 10.

    You can use strtoul() to convert binary numbers, by specifying a base argument of 2. There is no need to "split" the string, and leading zeroes won't matter of course (as they shouldn't, 000102 is equal to 102):

    const char *binary = "00010";
    unsigned long value;
    char *endp = NULL;
    
    value = strtoul(binary, &endp, 2);
    if(endp != NULL && *endp == '\0')
      printf("converted binary '%s' to integer %lu\n", binary, value);