简体   繁体   中英

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 ?

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

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

Operator precedence describes the order in which operations will occur. This is the same as PEMDAS in maths class and is to reduce the number of parentheses required. The == operator has a precedence of 9, & a precedence of 10, so the == operator grabs its arguments first.

This means that (a & b == c) is the same as (a & (b == c)) , which is not what you expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM