Converting char to binary strings and vice-versa

Keio203

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?

Dinindu Gunathilaka

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.

edited at
0

Comments

0 comments
Login to comment

Related

R - Converting formulae to character strings and vice versa

Converting Strings to encryption keys and vice versa java

C: Converting unsigned char array to signed int (vice versa)

Converting XDocument to XmlDocument and vice versa

Is converting from unsigned char to signed char and vice versa in C89 well defined?

Convert binary to ASCII and vice versa

Converting float NaN values from binary form and vice-versa results a mismatch

Converting a preorder traversal array to an level order traversal array (or vice versa) given that the binary tree was filled in Level Order

SAS: What is the quickest way to convert a dataset compressed in binary to compressed using char or vice versa?

Converting Secret Key into a String and Vice Versa

"Converting" Numpy arrays to Matlab and vice versa

"Converting" Numpy arrays to Matlab and vice versa

Converting pandas dataframe to dict and vice versa

Converting a population on a grid to coordinates, and vice versa

Converting QString to Ascii value & Vice Versa in Qt

Converting an Armadillo Matrix to an Eigen MatriXd and vice versa

Converting String to Byte Array and vice versa

Converting Double to Float and vice versa manually

Converting string to integer and vice versa in Python

Converting base 6 to decimal and vice versa in Python?

ByteBuffer - convert long to char array and vice versa

Casting a bitset to unsigned char, and vice versa

Binary to char converting in c

Converting data property to accessor property and vice versa in JavaScript

Converting Input text from lowercase to uppercase and vice versa in Javascript

Pandas : Converting Dataframe upper triangular to lower and vice versa

Converting from Instant to XMLGregorianCalendar and vice-versa without losing precision

Converting byte[] to json and vice versa without jackson or gson

Overhead of converting from []byte to string and vice-versa