问题描述
你如何设置、清除和稍微切换?
How do you set, clear, and toggle a bit?
推荐答案
设置一点
使用按位或运算符 (|
) 设置位.
number |= 1UL << n;
这将设置 number
的 n
th 位.n
应该为零,如果你想设置 1
st 位等等直到 n-1
,如果你想设置 n
th 位.
That will set the n
th bit of 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
th bit.
如果number
比unsigned long
更宽,则使用1ULL
;1UL << 在评估
1UL << 之后才会发生.n
移动超过 long
的宽度是未定义的行为.这同样适用于所有其他示例.
Use
1ULL
if number
is wider than unsigned long
; promotion of 1UL << n
doesn't happen until after evaluating 1UL << n
where it's undefined behaviour to shift by more than the width of a long
. The same applies to all the rest of the examples.
使用按位与运算符 (
&
) 清除位.
Use the bitwise AND operator (
&
) to clear a bit.
number &= ~(1UL << n);
这将清除
number
的 n
位.您必须使用按位非运算符 (~
) 反转位字符串,然后将其与.
That will clear the
n
th bit of number
. You must invert the bit string with the bitwise NOT operator (~
), then AND it.
XOR 运算符 (
^
) 可用于切换位.
The XOR operator (
^
) can be used to toggle a bit.
number ^= 1UL << n;
这将切换
number
的n
位.
你没有要求这个,但我不妨加上它.
You didn't ask for this, but I might as well add it.
要检查一点,将数字 n 右移,然后按位与它:
To check a bit, shift the number n to the right, then bitwise AND it:
bit = (number >> n) & 1U;
这会将
number
的第n
位的值放入变量bit
中.
That will put the value of the
n
th bit of number
into the variable bit
.
将
n
位设置为 1
或 0
可以通过以下 2 的补码 C++ 实现来实现:
Setting the
n
th bit to either 1
or 0
can be achieved with the following on a 2's complement C++ implementation:
number ^= (-x ^ number) & (1UL << n);
位
n
在x
为1
时置位,x
为0时清零.如果
x
有其他值,你会得到垃圾.x = !!x
将其布尔化为 0 或 1.
Bit
n
will be set if x
is 1
, and cleared if x
is 0
. If x
has some other value, you get garbage. x = !!x
will booleanize it to 0 or 1.
要使其独立于 2 的补码否定行为(其中
-1
已设置所有位,与 1 的补码或符号/幅度 C++ 实现不同),请使用无符号否定.
To make this independent of 2's complement negation behaviour (where
-1
has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.
number ^= (-(unsigned long)x ^ number) & (1UL << n);
或
unsigned long newbit = !!x; // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);
使用无符号类型进行可移植位操作通常是个好主意.
It's generally a good idea to use unsigned types for portable bit manipulation.
或
number = (number & ~(1UL << n)) | (x << n);
(number & ~(1UL << n))
将清除 n
位和 (x << n)
会将 n
th 位设置为 x
.
(number & ~(1UL << n))
will clear the n
th bit and (x << n)
will set the n
th bit to x
.
通常最好不要复制/粘贴代码,因此很多人使用预处理器宏(例如 社区维基进一步回答)或某种封装.
It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down) or some sort of encapsulation.
这篇关于您如何设置、清除和切换单个位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!