[英]C++ Bit masking with AND operation within if statement
I have an integer input and I should check every bit, whether it's 0 or 1. I have a code example that should print "result is 0", but it printed "result is 1".我有一个整数输入,我应该检查每一位,无论是 0 还是 1。我有一个代码示例应该打印“结果为 0”,但它打印“结果为 1”。
#include <iostream>
using namespace std;
int main() {
int mask = 0x80;
int input = 0x03;
if ((mask && input) == 0) {
cout << "result is 0" << endl;
} else {
cout << "result is 1" << endl;
}
}
if ((mask && input) == 0)
. if ((mask && input) == 0)
。 &&
is the logical AND operator. &&
是逻辑与运算符。 Because both mask
and input
is not equal to 0, it will return true
.因为
mask
和input
都不等于 0,所以它会返回true
。 (true && true)
is true
, true == 0
is false
. (true && true)
为true
, true == 0
为false
。 The condition is false
, so everything in else
get executed, hence the result.条件为
false
,所以else
所有else
都会被执行,因此结果。
You should change &&
to &
(bitwise AND operator)您应该将
&&
更改为&
(按位 AND 运算符)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.