简体   繁体   中英

how to convert a char to binary?

is there a simple way to convert a character to its binary representation?

Im trying to send a message to another process, a single bit at a time. So if the message is "Hello", i need to first turn 'H' into binary, and then send the bits in order.

Storing in an array would be preferred.

Thanks for any feedback, either pseudo code or actual code would be the most helpful.

I think I should mention this is for a school assignment to learn about signals... it's just an interesting way to learn about them. SIGUSR1 is used as 0, SIGUSR2 is used as 1, and the point is to send a message from one process to another, pretending the environment is locking down other methods of communication.

You have only to loop for each bit do a shift and do an logic AND to get the bit.

for (int i = 0; i < 8; ++i) {
    send((mychar >> i) & 1);
}

For example:

unsigned char mychar = 0xA5; // 10100101

(mychar >> 0)    10100101
& 1            & 00000001
=============    00000001 (bit 1)

(mychar >> 1)    01010010
& 1            & 00000001
=============    00000000 (bit 0)

and so on...

What about:

int output[CHAR_BIT];
char c;
int i;
for (i = 0; i < CHAR_BIT; ++i) {
  output[i] = (c >> i) & 1;
}

That writes the bits from c into output , least significant bit first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM