使我感到沮丧的代码如下:

bool a = 0x00000FF0 & 0x00000FF0 == 0x00000FF0;
if (a) {
  Serial.println("True");
} else {
  Serial.println("False");
}

这将打印“False”。我真的不明白为什么。
一些更多的测试:
bool a = 0x00000FF0 & 0x00000FF0 == 0x00000FF0;
Serial.println(a);

打印0

和:
unsigned long a = 0x00000FF0 & 0x00000FF0;
Serial.println(a, HEX);

打印FF0

最佳答案

运算符优先级,带有警告:

warning: suggest parentheses around comparison in operand of ‘&’ [-Wparentheses]

改成
bool a = (0x00000FF0 & 0x00000FF0) == 0x00000FF0;

关于c++ - 按位运算结果和 bool 值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26935397/

10-11 19:10