如何从位数组变为字节?

How can I go from a bit array to an byte?

本文关键字:字节 数组      更新时间:2023-10-16

我有这个位数组

int bits[8] = { 0, 1, 1, 0, 0, 1, 0, 1 }

十六进制为 65,十进制为 101。ASCII 字母是"e"。如何将数组读取为 char 和 int(十进制值(?

您可以使用位移位来从位数组中获取字符,如下所示:

int bits[8] = { 0, 1, 1, 0, 0, 1, 0, 1 };
char result = 0; // store the result
for(int i = 0; i < 8; i++){
result += (bits[i] << (7 - i)); // Add the bit shifted value
}
cout << result;

这基本上是遍历数组,按正确的量进行位移,然后将值添加到聚合的"结果"变量中。输出应为"e"。