我的目标是通过为每个位分配值来构建 char 变量,即我需要为每个位分配 0 和 1。
我做了以下代码:
char packet;
int bit;
packet &= ~(1 << 0);
packet |= (1 << 1);
printf("\n Checking each bit of packet: \n");
for(int x=0;x<2;x++)
{
bit = packet & (1 << x);
printf("\nBit [%d] of packet : %d", x, bit);
}
但是我得到的输出是:
Bit[0] of packet : 0 Bit[1] of packet : 2
这里有什么问题吗?
最佳答案
这里没有问题,输出是正确的。
原因如下:
当您使用 |=
设置数据包的值时,值为10
以十进制表示为 2。当您分配 packet & (1 << x)
时至bit
,您实际上分配了值 2(二进制的 10
)。
To determine whether the second bit is 1, a bitwise AND is applied to it and another bit pattern containing 1 in the second bit:
0011 (decimal 3)
AND 0010 (decimal 2)
= 0010 (decimal 2)
如果您的目的只是检查 bool 值是否已设置该位,只需将其转换为 bool 值即可。
(希望一切都有意义,我有点累了;))
关于c - 操作字符变量的位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5495417/