Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare uint8_t with hexadecimal in C++

Tags:

c++

atmega

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.

like image 683
Zulakis Avatar asked Oct 24 '25 12:10

Zulakis


1 Answers

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

like image 176
PSkocik Avatar answered Oct 26 '25 01:10

PSkocik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!