Bitwise Operation Result and Logical Operations

The code that upsets me is as follows:

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

Prints "False". I really don'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); 

outputs FF0 .

+6
source share
3 answers

Operator priority, compile with warnings:

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

Change to

 bool a = (0x00000FF0 & 0x00000FF0) == 0x00000FF0; 
+8
source

Considering the priority of the operator , it analyzes how

 0x00000FF0 & (0x00000FF0 == 0x00000FF0) 

if you want to

 (0x00000FF0 & 0x00000FF0) == 0x00000FF0 

Add parentheses and you get the expected result.

+7
source

This is a simple matter of priority.

From the sound of things, you assume that: 0x00000FF0 & 0x00000FF0 == 0x00000FF0; will be considered as: (0x00000FF0 & 0x00000FF0) == 0x00000FF0; , but in fact it is the same as: 0x00000FF0 & (0x00000FF0 == 0x00000FF0); .

In the latter case, the result is clearly false - == creates either 0 or 1 , and 0xff0 & 1 and 0xff0 & 0 , or both 0 values.

+5
source

Source: https://habr.com/ru/post/978204/


All Articles