3

Let's say I have uint8_t bytes[maxBytes];.

Now I want to compare the lower 6 bits of the first byte (bytes[0]) with 0x3c.

I tried to do it like this:

bytes[0] & 0x3f == 0x3c

Unfortunately, this did not produce the expected result. (i.e. it's always false, even though when I print out bytes[0] & 0x3f , it is 0x3c)

I've played around with this some more and found out that

bytes[0] & 0x00 == 0x00

is sometimes true, and sometimes false. (Same with bytes[0] & 0x0 == 0x0 and bytes[0] & 0x00 == 0x0). Shouldn't it always be true?

What is going on here? How can I make my 0x3c comparison work?

Sitenote: I'm running this code on an arduino w/ atmega328pb MCU.

Zulakis
  • 7,859
  • 10
  • 42
  • 67
  • 3
    Possible duplicate of [Operator precedence (bitwise '&' lower than '==')](https://stackoverflow.com/questions/4685072/operator-precedence-bitwise-lower-than) – Axalo Feb 28 '19 at 23:29
  • 1
    out of the missing (), if you want to compare with _0x3d_ why do you compare with _0x3c_ ? – bruno Feb 28 '19 at 23:31
  • `auto value = bytes[0] & 0x3f;` then do `if (value == 0x3d) ...` – Eljay Feb 28 '19 at 23:40
  • 1
    read compiler warnings and you'll find out the root cause immediately. For example [gcc says *warning: & has lower precedence than ==; == will be evaluated first \[-Wparentheses\]*](https://godbolt.org/z/aklyuM) – phuclv Mar 01 '19 at 02:24
  • @bruno that was a typo. fixed. – Zulakis Mar 01 '19 at 08:38

1 Answers1

5

You need parentheses:

(bytes[0] & 0x3f) == 0x3c

This is because of the weird precedences of & and | which were inherited from C, which inherited them from B (Dennis Ritchie described this precedence problem in https://www.bell-labs.com/usr/dmr/www/chist.html).

user4581301
  • 33,082
  • 7
  • 33
  • 54
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142