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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With