Search code examples
arrayscbinaryhexdata-conversion

Convert char array elements into Hexadecimal equivalent in C code


I'm currently trying to create a custom function in C code that would take an unsigned char array like: array[] = "11000000111111111000000010000000" as the input and convert this into 0xC0FF8080 and either store this back into array or simply printf to the console. Any help in clearing up my confusion on this would be greatly appreciated. Thanks!


Solution

  • Iterate over the string, and with each iteration shift the result to the left and set the right-most bit to the appropriate value:

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char const array[] = "11000000111111111000000010000000";
        size_t const length = strlen(array);
    
        unsigned long long n = 0ULL;
        for (size_t idx = 0U; idx < length; ++idx)
        {
            n <<= 1U;
            n |= array[idx] == '0' ? 0U : 1U;
            // n |= array[idx] - '0'; // An alternative to the previous line
        }
    
        printf("%#llx\n", n);
    }
    

    This uses a (signed) char array, but the method is the same.

    Storing the result back into the char array:

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char array[] = "11000000111111111000000010000000";
        size_t length = strlen(array);
    
        for (size_t idx = 0U; idx < length; ++idx)
            array[idx] = array[idx] - '0';
    
        for (size_t idx = 0U; idx < length; ++idx)
            printf("%d", array[idx]);
        putchar('\n');
    }
    

    Note that here the char types will hold the decimal values 0 and 1.