如何设置、清除和切换单个位?

新手上路,请多包涵

如何设置、清除和切换一点?

原文由 JeffV 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 387
2 个回答

设置一点

使用按位或运算符 ( | ) 设置一个位。

 number |= 1UL << n;

这将设置 n 的第 number 位。 n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n 位。

使用 1ULL 如果 numberunsigned long 宽;提升 1UL << n 直到评估 1UL << n 之后才会发生,在这种情况下,移动超过 long 的宽度是未定义的行为。这同样适用于所有其余示例。

清除一点

使用按位与运算符 ( & ) 清除位。

 number &= ~(1UL << n);

这将清除 n 的第 number 位。您必须使用按位 NOT 运算符 ( ~ ) 反转位字符串,然后将其与。

切换一下

XOR 运算符 ( ^ ) 可用于切换位。

 number ^= 1UL << n;

这将切换 n 的第 number 位。

检查了一下

你没有要求这个,但我不妨添加它。

要检查一下,请将数字 n 向右移动,然后按位与它:

 bit = (number >> n) & 1U;

这会将 n 的第 number 的值放入变量 bit 中。

将第 n 位更改为 x

n 第位设置为 10 可以通过以下在 2 的补码 C++ 实现中实现:

 number ^= (-x ^ number) & (1UL << n);

Bit n will be set if x is 1 , and cleared if x is 0 .如果 x 有其他值,你会得到垃圾。 x = !!x 会将其布尔化为 0 或 1。

要使其独立于 2 的补码否定行为(其中 -1 已设置所有位,与 1 的补码或符号/大小 C++ 实现不同),请使用无符号否定。

 number ^= (-(unsigned long)x ^ number) & (1UL << n);

或者

unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);

使用无符号类型进行可移植位操作通常是一个好主意。

或者

number = (number & ~(1UL << n)) | (x << n);

(number & ~(1UL << n)) will clear the n th bit and (x << n) will set the n th bit to x .

通常不要复制/粘贴代码通常也是一个好主意,因此很多人使用预处理器宏(如 社区 wiki 回答进一步向下)或某种封装。

原文由 Paige Ruten 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是 C 中执行基本按位运算的例程:

 #define INT_BIT (unsigned int) (sizeof(unsigned int) * 8U) //number of bits in unsigned int

int main(void)
{

    unsigned int k = 5; //k is the bit position; here it is the 5th bit from the LSb (0th bit)

    unsigned int regA = 0x00007C7C; //we perform bitwise operations on regA

    regA |= (1U << k);    //Set kth bit

    regA &= ~(1U << k);   //Clear kth bit

    regA ^= (1U << k);    //Toggle kth bit

    regA = (regA << k) | regA >> (INT_BIT - k); //Rotate left by k bits

    regA = (regA >> k) | regA << (INT_BIT - k); //Rotate right by k bits

    return 0;
}

原文由 lckid2004 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题