cif-statementbitwise-operatorsendiannessunsigned-long-long-int

C if condition comparing result of unsigned long bitwise operation with 0 is evaluated as false although true expected ( 0 == 0 is false)


versionNumberAndPlaceNumber being 0xFFFF00 the true case of the following if is not entered:

if(versionNumberAndPlaceNumber & 0xFFUL == 0UL) {

Why would this be?

.

Here follows a longer code excerpt:

if(bytes_received == 27) {      // the data size of "struct bee" (padded), version number (8 bits) and place number of struct place
printf("\n27\n");
                unsigned long versionNumberAndPlaceNumber = 0;
                memcpy(&versionNumberAndPlaceNumber, &(read[24]), 8);     // read 8 = sizeof(long) on x64 bytes, hope it's faster than transferring less bytes on x64 (into possibly a register)
                /* memcpy copies bytes from increasing source address to increasing destination address, x64 this is supposed to run on is Little Endian thus for example [0xFF, 0x00, ...] as an unsigned long is ...0000000011111111 = 255 */
printf("\n%lu\n", versionNumberAndPlaceNumber);
                if(versionNumberAndPlaceNumber & 0xFFUL == 0UL) {          // version 0 of data for version 0 of this server
printf("\nv correct\n");
                    unsigned long location[3];

(Note the read buffer is 32 bytes.)

And here's the output:

27

16776960

.

Debugging:

Instead of printing versionNumberAndPlaceNumber I also printed the whole if condition (indicating %d instead of %lu) and got 0 as output thus the condition appears to be false.

But 16776960 = 0xFFFF00 and 0xFFFF00 AND 0xFF is 0.

Why is 0 == 0 false ?


Solution

  • == operator has higher operator precedence, than & (bitwise AND) therefore your condition is equal to this

    if(versionNumberAndPlaceNumber & (0xFFUL == 0UL)) // 0xFFFF00 & 0 -> 0 -> false