-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!

4
  • 2
    Be more specific: what have you tried so far? What is your confusion's cause? Commented Aug 23, 2021 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. Commented Aug 23, 2021 at 15:25
  • Also see stackoverflow.com/questions/5307656/… and a myriad of other solutions posted online and Google-able. Commented Aug 23, 2021 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.) Commented Aug 23, 2021 at 16:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
@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?
you were correct, I didn't copy it correctly. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.