如何设置,清除和切换单个位? [英] How do you set, clear, and toggle a single bit?
问题描述
如何设置,清除和切换位?
How do you set, clear, and toggle a bit?
推荐答案
设置位
使用按位或运算符(|
)设置一个位.
number |= 1UL << n;
这将设置number
的第n
位.如果要设置1
st位,将n
设置为零;如果要设置n
th位,将n-1
设置为n-1
.
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
;否则,请使用1ULL
.直到评估了1UL << n
之后,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.
使用按位AND运算符(&
)清除一位.
Use the bitwise AND operator (&
) to clear a bit.
number &= ~(1UL << n);
这将清除number
的第n
位.您必须使用按位NOT运算符(~
)反转位字符串,然后将其取反.
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
.
使用2的补码C ++实现,可以将第n
位设置为1
或0
:
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);
如果x
是1
,则
位n
将被置位,如果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
位设置为x
.
(number & ~(1UL << n))
will clear the n
th bit and (x << n)
will set the n
th bit to x
.
通常不要复制/粘贴代码也是一个好主意,因此很多人使用预处理器宏(例如社区Wiki进一步回答)或某种封装.
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.
这篇关于如何设置,清除和切换单个位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!