In my example im creating an integer variable called testVar and i make it equal to a1 in hex. when printing out the variable it shows that it should indeed be equal to a1 in hex. Now when checking if testVar is equal to a1 in an if statement, the if statement only executes when there is no mask applied to the variable.
My question "is why these if statements don’t execute when the variable has a mask applied to it?".
#include <stdio.h>
int testVar = 0xa1; //testVar should equal 0x000000a1 now
void main(){
printf("%x \n",testVar); //should prove that testVar is indeed equal to a1 in hex
printf("%x \n",testVar & 0x000000ff); //both printf functions are outputting a1
if (testVar == 0x000000a1){ //this if statement works!
printf("success1");
}
if (testVar & 0x000000ff == 0x000000a1){ //this doesn't execute
printf("success2");
}
if (testVar & 0x000000ff == 0xa1){ //this doesn't execute
printf("success3");
}
}
>Solution :
The equality operator == has higher precedence than the binary bitwise-AND operator &. That means that this:
if (testVar & 0x000000ff == 0x000000a1)
Parses as this:
if (testVar & (0x000000ff == 0x000000a1))
Which is not what you want. Use parenthesis to ensure proper grouping:
if ((testVar & 0x000000ff) == 0x000000a1)
And similarly:
if ((testVar & 0x000000ff) == 0xa1)