从位数组中重构一个值
Reconstructing a value from an array of bits
我有一个位数组(存储为布尔值),我想将其重构为整数。我想从右边插入位,然后在数组的每一个位上向左移动。
如何在LSB侧插入位并同时将其移位?
你可以这样做:
bool yourarray[32];
int output = 0;
for(int i = 0; i < 32; i++)
{
// Shift the bits left by 1. The first time through the loop this
// will have no real effect since 0 << 1 == 0.
output <<= 1;
// If this particular bit is "on", activate the LSB using a bitwise-or
if(yourarray[i] == true)
output |= 1; // this turns on the LSB
// We could also do this for completeness, but it has no effect since
// the LSB is already 0:
else
output &= ~1; // this turns off the LSB
}
这里我假设int的大小是32
还有其他需要考虑的因素,比如端序,但这应该给你一个概念。还要注意符号问题,因为在这种情况下,最高(最左边)位将影响int输出是正还是负。
这只是对使用位运算符时发生的情况进行一些解释。
假设我们有一个1字节(8位)的值:val1 = 00000011。我们有另一个1字节的值:val2 =00100001
如果我们把val1的位左移2位,像这样:
val1 = val1 << 2;
val1现在看起来像这样:00001100.
然后,如果我们像这样用(|)val2与val1进行OR运算:
val1 = val1 | val2
val1看起来像这样:00101101.
我希望这对你有帮助^_^