如何从 8 个布尔值中创建一个字节(反之亦然)? [英] How to create a byte out of 8 bool values (and vice versa)?

查看:35
本文介绍了如何从 8 个布尔值中创建一个字节(反之亦然)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

请注意,在编写另一个联合成员之后读取一个联合成员在 ISO C99 中是明确定义的,并且作为几个主要 C++ 实现(包括 MSVC 和 GNU 兼容的 C++ 编译器)的扩展,但在 ISO C++ 中是未定义行为.memcpyC++20 std::bit_cast 是在可移植 C++ 中键入双关语的安全方法.

Note that reading one union member after writing another is well-defined in ISO C99, and as an extension in several major C++ implementations (including MSVC and GNU-compatible C++ compilers), but is Undefined Behaviour in ISO C++. memcpy or C++20 std::bit_cast are the safe ways to type-pun in portable C++.

(另外,char 中位域的位序是 实现定义,位域成员之间可能的填充.)

(Also, the bit-order of bitfields within a char is implementation defined, as is possible padding between bitfield members.)

这篇关于如何从 8 个布尔值中创建一个字节(反之亦然)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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