更新时间:2023-12-05 20:31:34
简答
您想对当前值的位与操作用的Bitwise不你想取消设置在标志的操作。按位非反转每个比特(即0 => 1,1 => 0)。
标志=标志和放大器; 〜MASK;
或标记和放大器; =〜MASK;
长的答案
ENABLE_WALK = 0 // 00000000
ENABLE_RUN = 1 // 00000001
ENABLE_SHOOT = 2 // 00000010
ENABLE_SHOOTRUN = 3 // 00000011值= ENABLE_RUN // 00000001
值| = ENABLE_SHOOT // 00000011或相同ENABLE_SHOOTRUN
当您执行的位与价值的按位不是你想要取消设置。
值=价值和放大器; 〜ENABLE_SHOOT // 00000001
你实际上是这样做的:
0 0 0 0 0 0 1 1(当前值)
&安培; 1 1 1 1 1 1 0 1(〜ENABLE_SHOOT)
---------------
0 0 0 0 0 0 0 1(结果)
There is a variable that holds some flags and I want to remove one of them. But I don't know how to remove it.
Here is how I set the flag.
my.emask |= ENABLE_SHOOT;
Short Answer
You want to do an Bitwise AND operation on the current value with a Bitwise NOT operation of the flag you want to unset. A Bitwise NOT inverts every bit (i.e. 0 => 1, 1 => 0).
flags = flags & ~MASK;
or flags &= ~MASK;
.
Long Answer
ENABLE_WALK = 0 // 00000000
ENABLE_RUN = 1 // 00000001
ENABLE_SHOOT = 2 // 00000010
ENABLE_SHOOTRUN = 3 // 00000011
value = ENABLE_RUN // 00000001
value |= ENABLE_SHOOT // 00000011 or same as ENABLE_SHOOTRUN
When you perform a Bitwise AND with Bitwise NOT of the value you want unset.
value = value & ~ENABLE_SHOOT // 00000001
you are actually doing:
0 0 0 0 0 0 1 1 (current value)
& 1 1 1 1 1 1 0 1 (~ENABLE_SHOOT)
---------------
0 0 0 0 0 0 0 1 (result)