问题描述
我有8个bool
变量,我想将它们合并"为一个字节.
I have 8 bool
variables, and I want to "merge" them into a byte.
是否有一种简单/首选的方法来做到这一点?
Is there an easy/preferred method to do this?
反过来,将一个字节解码为8个独立的布尔值又如何呢?
How about the other way around, decoding a byte into 8 separate boolean values?
我假设这不是一个不合理的问题,但是由于我无法通过Google找到相关文档,因此这可能是您的直觉都不正确"的另一种情况.
I come in assuming it's not an unreasonable question, but since I couldn't find relevant documentation via Google, it's probably another one of those "nonono all your intuition is wrong" cases.
推荐答案
困难的方法:
unsigned char ToByte(bool b[8])
{
unsigned char c = 0;
for (int i=0; i < 8; ++i)
if (b[i])
c |= 1 << i;
return c;
}
并且:
void FromByte(unsigned char c, bool b[8])
{
for (int i=0; i < 8; ++i)
b[i] = (c & (1<<i)) != 0;
}
或者很酷的方式:
struct Bits
{
unsigned b0:1, b1:1, b2:1, b3:1, b4:1, b5:1, b6:1, b7:1;
};
union CBits
{
Bits bits;
unsigned char byte;
};
然后,您可以分配给工会的一个成员,并从另一个成员中读取.但是请注意,Bits
中的位顺序是由实现定义的.
Then you can assign to one member of the union and read from another. But note that the order of the bits in Bits
is implementation defined.
这篇关于如何从8个bool值中创建一个字节(反之亦然)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!