Why must I use the ~ operator when clearing a bit?
This question already has an answer here:
If you want to set a bit at third place from the right :
Y : 01001000
1 << 2 : 00000100
Y | (1 << 2) : 01001100 The | is OR, bits are set to 1 if any is 1.
If you want to remove the bit :
1 << 2 : 00000100
~(1 << 2) : 11111011 The ~ is NOT, bits are inversed
Y : 01001100
Y & ~(1 << 2) : 01001000 The & is AND, bits are set to 1 if both are 1.
I suggest you read more about Bitwise operators
No, ~
has nothing to do with interpreting the number as negative: tilde ~
operator interprets the number as a pattern of bits, which it then inverts (ie replaces zeros with ones and ones with zeros). In fact, if you apply ~
to an unsigned value, the result would remain positive.
Recall that 1 << k
expression produces a pattern of all zeros and a single 1
at the position designated by k
. This is a bit mask that can be used to force bit at position k
to 1
by applying OR operation.
Now consider what happens when you apply ~
to it: all 0
s would become 1
s, and the only 1
would become zero. Hence, the result is a bit mask suitable for forcing a single bit to zero by applying AND operation.
The ~
operator turns all of the 0's to 1's and all of the 1's to 0's. In order to clear the bint in position n you want to and it will all ones and a zero in the nth position so shift a one to the nth position and ~
invert all the bits.
上一篇: 我如何设置C中整数的最低有效位
下一篇: 为什么我必须在清除一点时使用〜运算符?