c - 操作字符变量的位

标签 c bit-manipulation bitwise-operators

我的目标是通过为每个位分配值来构建 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)。

Wikipedia entry:

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/

相关文章:

c - 如何在c中屏蔽密码?

c - 在C中查找字符串数组的长度

c++ - 按位比较

java - "com.mysql.jdbc.MysqlDataTruncation: Data truncation: Out of range value"与按位 'OR'

构造一个逻辑表达式,它将计算一个字节中的位

c - 按位运算 : Need to create a large integer, 但只能声明一个8bit整数

C:fread返回0

c - 在图案打印程序中得到错误的答案

assembly - "shift operates on bits individually"是什么意思?

python - 如何在使用按位运算添加两个整数时添加无限循环的代码修复