cif-statementhexmask

An 'if' statement isn't executing when a mask is applied to a variable even though it should


In my example, I’m creating an integer variable called testVar and I make it equal to A1 in hexadecimal. When printing out the variable, it shows that it should indeed be equal to A1 in hexadecimal. Now when checking if testVar is equal to A1 in an if statement, the if statement only executes when there isn't any mask applied to the variable.

Why don't these if statements execute when the variable has a mask applied to it?

#include <stdio.h>

int testVar = 0xA1;   // testVar should be equal 0x000000A1 now

void main() {
    printf("%x \n", testVar);               // Should prove that testVar is indeed equal to A1 in hexadecimal
    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 parentheses to ensure proper grouping:

    if ((testVar & 0x000000ff) == 0x000000a1)
    

    And similarly:

    if ((testVar & 0x000000ff) == 0xa1)