Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino and Bitwise, unexpected result

Tags:

arduino

Getting my self a bit confused here.

I would like to test if a set of bits (3 bits) contains a bit in a certain postion.

if (B110 & B010 == B010)

(B110 being the number to check, B010 the bit I want to see if is there)

The above code isn't giving me the expected out come, both B110 is true and B101 is true. I am pretty sure that I need to use a &(and) to test with the mask B010.

My understanding is that B110 & B010 would be equal to B010 and that B101 & B010 would equal B000. But my if statement is run with both test bits?

I am coding in an Arduino, I'm sure that it's a simple misunderstanding on my behalf but not sure where.

like image 803
Ashley Hughes Avatar asked Jun 21 '11 11:06

Ashley Hughes


2 Answers

Try if ((B110 & B010) == B010)

At the moment it's running as if (B110 & (B010 == B010)) which will always be true.

As this table shows, == and != have a higher precedence than &, | etc.

like image 179
Majenko Avatar answered Oct 18 '22 09:10

Majenko


The "== B010" is actually unnecessary in this test. In C, 0 represents "false," while any nonzero value is considered "true." B110 & B010 (or any other value with that bit set) will return B010, which is not equal to 0, so the test succeeds.

like image 25
spwert Avatar answered Oct 18 '22 08:10

spwert