1

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 ?

user5588495
  • 76
  • 1
  • 6
  • 3
    The condition `(a & b == c)` is the same as `(a & (b == c))`. – pmg Apr 06 '20 at 10:01
  • right, when I looked up the C operator precedence I glanced too briefly and mixed the "&" address operator with the "&" bitwise operator. The address operator has higher precedence than the `==` but the bitwise oeprator hasn't. – user5588495 Apr 06 '20 at 10:05
  • 1
    If in doubt with a complex expression, use brackets, else use brackets. – Martin James Apr 06 '20 at 11:11

2 Answers2

1

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

if(versionNumberAndPlaceNumber & (0xFFUL == 0UL)) // 0xFFFF00 & 0 -> 0 -> false
Eraklon
  • 4,206
  • 2
  • 13
  • 29
1

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.

unDeadHerbs
  • 1,306
  • 1
  • 11
  • 19