The code that frustrates me is as follows:
bool a = 0x00000FF0 & 0x00000FF0 == 0x00000FF0;
if (a) {
Serial.println("True");
} else {
Serial.println("False");
}
This prints "False". I really can't understand why. Some more tests:
bool a = 0x00000FF0 & 0x00000FF0 == 0x00000FF0;
Serial.println(a);
prints 0
.
And:
unsigned long a = 0x00000FF0 & 0x00000FF0;
Serial.println(a, HEX);
prints FF0
.
Mixing bitwise and relational operators in the same full expression can be a sign of a logic error in the expression where a logical operator is usually the intended operator.
The key difference between Bitwise and Logical operators is that Bitwise operators work on bits and perform bit by bit operations while logical operators are used to make a decision based on multiple conditions.
A little bit more into explaining how shift works with a boolean. So true as you said will be 1 and false will be 0.
First, logical operators work on boolean expressions and return boolean values (either true or false), whereas bitwise operators work on binary digits of integer values (long, int, short, char, and byte) and return an integer.
Operator precedence, compile with warnings:
warning: suggest parentheses around comparison in operand of ‘&’ [-Wparentheses]
Change to
bool a = (0x00000FF0 & 0x00000FF0) == 0x00000FF0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With