2

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?

Keio203
  • 123
  • 3

1 Answers1

1

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 */
        
    }
}
  • 1
    I think it's quite close to what I need, but how can you store the result in a char array instead of printing it? – Keio203 Apr 16 '22 at 05:13
  • 1
    What do you mean by that?Do you want to store a-z binary values or you wanna store binary strings for a given string(array of characters)? Could you please be more specific? – Dinindu Gunathilaka Apr 16 '22 at 05:30