Search code examples
c++atmega

Compare uint8_t with hexadecimal in C++


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.


Solution

  • 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).