如何设置、清除和切换一点?
原文由 JeffV 发布,翻译遵循 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 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
设置一点
使用按位或运算符 (
|
) 设置一个位。这将设置
n
的第number
位。n
should be zero, if you want to set the1
st bit and so on upton-1
, if you want to set then
位。使用
1ULL
如果number
比unsigned long
宽;提升1UL << n
直到评估1UL << n
之后才会发生,在这种情况下,移动超过long
的宽度是未定义的行为。这同样适用于所有其余示例。清除一点
使用按位与运算符 (
&
) 清除位。这将清除
n
的第number
位。您必须使用按位 NOT 运算符 (~
) 反转位字符串,然后将其与。切换一下
XOR 运算符 (
^
) 可用于切换位。这将切换
n
的第number
位。检查了一下
你没有要求这个,但我不妨添加它。
要检查一下,请将数字 n 向右移动,然后按位与它:
这会将
n
的第number
的值放入变量bit
中。将第 n 位更改为 x
将
n
第位设置为1
或0
可以通过以下在 2 的补码 C++ 实现中实现:Bit
n
will be set ifx
is1
, and cleared ifx
is0
.如果x
有其他值,你会得到垃圾。x = !!x
会将其布尔化为 0 或 1。要使其独立于 2 的补码否定行为(其中
-1
已设置所有位,与 1 的补码或符号/大小 C++ 实现不同),请使用无符号否定。或者
使用无符号类型进行可移植位操作通常是一个好主意。
或者
(number & ~(1UL << n))
will clear then
th bit and(x << n)
will set then
th bit tox
.通常不要复制/粘贴代码通常也是一个好主意,因此很多人使用预处理器宏(如 社区 wiki 回答进一步向下)或某种封装。