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!
1 Answer
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.
3 Comments
Tyler Mckean
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?
Yun
@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?Tyler Mckean
you were correct, I didn't copy it correctly. Thanks so much!
strtoul(array, NULL, 2)to convert to anunsigned long, then printf it back out using%lX. (Orsnprintfto convert to a string.)