简体   繁体   English

如何将char转换为二进制?

[英]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. 因此,如果消息是“Hello”,我需要先将“H”转换为二进制,然后按顺序发送这些位。

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. SIGUSR1用作0,SIGUSR2用作1,并且点是从一个进程向另一个进程发送消息,假装环境正在锁定其他通信方法。

You have only to loop for each bit do a shift and do an logic AND to get the bit. 你只需要为每个位循环执行一次移位并执行逻辑AND来获取该位。

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. 它将c的位写入output ,最低位先写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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