如何将char转换为二进制? [英] how to convert a char to binary?

查看:16
本文介绍了如何将char转换为二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法可以将字符转换为其二进制表示?

is there a simple way to convert a character to its binary representation?

我正在尝试一次向另一个进程发送一条消息.所以如果消息是你好",我需要先把'H'转成二进制,然后按顺序发送.

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.

最好存储在数组中.

感谢您的任何反馈,无论是伪代码还是实际代码都将是最有帮助的.

Thanks for any feedback, either pseudo code or actual code would be the most helpful.

我想我应该提到这是一个学习信号的学校作业......这只是了解它们的一种有趣方式.SIGUSR1 用作 0,SIGUSR2 用作 1,重点是从一个进程向另一个进程发送消息,假装环境正在锁定其他通信方式.

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.

推荐答案

你只需要循环为每个位做一个移位并做一个逻辑 AND 来得到这个位.

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);
}

例如:

unsigned char mychar = 0xA5; // 10100101

(mychar >> 0)    10100101
& 1            & 00000001
=============    00000001 (bit 1)

(mychar >> 1)    01010010
& 1            & 00000001
=============    00000000 (bit 0)

等等……

这篇关于如何将char转换为二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆