Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a char to binary?

Tags:

c

char

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.

like image 693
Blackbinary Avatar asked Feb 03 '11 22:02

Blackbinary


2 Answers

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...

like image 128
Murilo Vasconcelos Avatar answered Nov 08 '22 06:11

Murilo Vasconcelos


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.

like image 43
Jeremiah Willcock Avatar answered Nov 08 '22 05:11

Jeremiah Willcock