I need to store an 8-bit string into a char variable and vice-versa (convert a char into an 8-bit string). What is the best way to do this? For example, if I want to store the 8-bit string 01010110 I could do like in this post Convert from a binary to char in C
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *data = "01010110";
char c = strtol(data, 0, 2);
}
How can I do the opposite?
I hope this is what you were searching for. This mechanism can be used to convert a char into an 8-bit string.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char c = 'a';
int mask = 0x80; /* 10000000 */
while (mask>0) {
printf("%d", (c & mask) > 0 );
mask >>= 1; /* move the bit down */
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments