C语言 如何将字符转换为二进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4892579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:42:57  来源:igfitidea点击:

how to convert a char to binary?

cbinarychar

提问by Blackbinary

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.

我试图向另一个进程发送一条消息,一次一个。所以如果消息是“你好”,我需要先把'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,重点是从一个进程向另一个进程发送消息,假装环境正在锁定其他通信方法。

回答by Murilo Vasconcelos

You have only to loop for each bit do a shift and do an logic ANDto 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...

等等...

回答by Jeremiah Willcock

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 cinto output, least significant bit first.

这首先将位c写入output, 最低有效位。