创建了8布尔值(反之亦然)的一个字节?

编程入门 行业动态 更新时间:2024-10-05 15:31:15
本文介绍了创建了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布尔值(反之亦然)的一个字节?

本文发布于:2023-11-03 04:09:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554205.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字节   布尔值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!