[英]bitwise AND in C++
I have defined an enum like this: 我已经定义了这样的枚举:
enum blStatus {
Class1 = 0x40, /* 0000,0100,0000 */
Class2 = 0x80, /* 0000,1000,0000 */
Class3 = 0x100, /* 0001,0000,0000 */
Class4 = 0x200 /* 0010,0000,0000 */
}
Now, somewhere in the code I have: 现在,在我的代码中的某个地方:
if ( status &= Class1 )
++c1;
else if ( status &= Class2 )
++c2;
else if ( status &= Class3 )
++c3;
else if ( status &= Class4 )
++c4;
Assume, the status hat this value: 假设,状态为此值:
status = 143 /* 0000,1000,1111 */
While debugging, none of the conditions is true. 在调试时,没有任何条件成立。 However "status &= Class2" is:
但是“status&= Class2”是:
0000,1000,1111 & 0000,1000,0000 = 0000,1000,0000
and the c2 counter must be incremented. 并且c2计数器必须递增。 but while debugging, all conditions are passed (ignored) and no counter increment.
但在调试时,所有条件都被传递(忽略)并且没有计数器增量。 Why?
为什么?
Use & instead of &=. 使用&而不是&=。
When you do x &= y you are getting: 当你做x&= y时,你得到:
x = x & y;
What you really want in your code: 您真正想要的代码:
if ( status & Class1 )
Now, after each if clause, you leave the value of status untouched. 现在,在每个if子句之后,您保持状态值不变。
This is because you are changing the status
in: 这是因为您要更改
status
:
if ( status &= Class1 )
status &= Class1
is same as status = status & Class1
as a result status changes to 0
: status &= Class1
与status = status & Class1
相同,因为结果状态更改为0
:
status = 0000 1000 1111
Class1 = 0000 0100 0000 &
-----------------------
status = 0000 0000 0000
Since you intend to just check the bits you don't need to do an assignment: 由于您只想检查不需要进行分配的位:
if ( status & Class1 )
因为if ( status &= Class1 )
会将0分配给状态,所以在所有下一个条件中,status的值将为0,这样就不会执行任何条件,并且不会增加conter的值。
Operator &=
puts computation result into left operand (equals a = a & b
). 运算符
&=
将计算结果放入左操作数(等于a = a & b
)。 After computation the expression (status &= Class1)
the status
variable is 0
and all following conditions are FALSE
. 在计算表达式
(status &= Class1)
, status
变量为0
并且所有以下条件都为FALSE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.