创建了8布尔值(反之亦然)的一个字节? [英] Creating a byte out of 8 bool values (and vice versa)?

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

问题描述

我有8 布尔变量,我想将它们合并成一个字节。

I have 8 bool variables, and I want to "merge" them into a byte.

有一个简单/ prefered方法来做到这一点?
如何周围的其他方法,一个字节解码成8个独立的布尔值?

Is there an easy/prefered method to do this? How about the other way around, decoding a byte into 8 separate boolean values?

我来的假设它不是一个不合理的问题,但因为我无法找到通过谷歌相关的文件,它可能是那些一个又一个NONONO所有你的直觉是错的的情况。

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

还是很酷的方式:

Or the cool way:

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

然后就可以分配到联盟成员之一,并从另一个读取。但要注意的位,订单执行定义的。

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

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