-3

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!

  • 2
    Be more specific: what have you tried so far? What is your confusion's cause? – Luca Polito Aug 23 '21 at 15:13
  • First of all, if you are using binary, you probably want to go down to the bit level instead of the byte level. Each unsigned char has 8 bits of data, that's 7 data points wasted if you use an entire char per 1 or 0. – Cheetaiean Aug 23 '21 at 15:25
  • Also see https://stackoverflow.com/questions/5307656/how-do-i-convert-a-binary-string-to-hex-using-c and a myriad of other solutions posted online and Google-able. – Cheetaiean Aug 23 '21 at 15:26
  • Simply call `strtoul(array, NULL, 2)` to convert to an `unsigned long`, then printf it back out using `%lX`. (Or `snprintf` to convert to a string.) – Steve Summit Aug 23 '21 at 16:14

1 Answers1

0

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.

Yun
  • 3,056
  • 6
  • 9
  • 28
  • Thanks Yun! However, i'm receiving an error for the line "n |= array[idx] == '0' ? 0U : 1U" saying the expression must have pointer-to-object type. Any ideas on how to solve that? – Tyler Mckean Aug 23 '21 at 16:15
  • @TylerMckean You're welcome! I've just tried the code snippet and it compiles without warnings. Are you sure you've copied it correctly? Was `array` declared differently perhaps? – Yun Aug 23 '21 at 16:23
  • you were correct, I didn't copy it correctly. Thanks so much! – Tyler Mckean Aug 23 '21 at 16:53