[英]C++ Bit masking with AND operation within if statement
我有一个整数输入,我应该检查每一位,无论是 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)
。 &&
是逻辑与运算符。 因为mask
和input
都不等于 0,所以它会返回true
。 (true && true)
为true
, true == 0
为false
。 条件为false
,所以else
所有else
都会被执行,因此结果。
您应该将&&
更改为&
(按位 AND 运算符)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.