How to convert char to binary?

Is there an easy way to convert a character to its binary representation?

I am trying to send a message to another process, one bit at a time. Therefore, if the message is "Hello", I need to first turn the "H" into a binary file, and then send the bit in order.

Saving in an array would be preferable.

Thanks for any feedback, the most useful can be either pseudo-code or valid code.

I think I should mention that it concerns a school assignment in order to learn about signals ... this is just an interesting way to learn about them. SIGUSR1 is used as 0, SIGUSR2 is used as 1, and the point should send a message from one process to another, pretending that the medium is blocking other communication methods.

+6
c char binary
source share
2 answers

You only have a loop for each bit, shift, and AND logic 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) 

etc.

+14
source share

What about:

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

This writes the bit from c to output , the least significant bit first.

+3
source share

All Articles