Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...