Bit Math Question

I must be missing something very basic about this but I’m new to using bitwise operators and haven’t been able to find anything that clarifies this.

If (0B00000010 & 0B00000010 == 0B00000010) {
// Do something
}

Why doesn’t this return true? I’m trying to check if a certain bit is high or not. Of course originally one of these was a variable but when it wouldn’t run I tried it like this. If I do the same with 0B00000001 it returns true. I’ve tried it in Hex too but same result. To get my functions to run I have to shift my bit of interest to the 1s place then & 1 == 1. What am I missing?

I suppose you use 'if' and not 'If' ?
Maybe try :
if ((0B00000010 & 0B00000010) == 0B00000010)

As lesept pointed out () are your friend. The == operator has higher precedence than & so is done first.

If you have your compiler warnings turned up, you will get a helpful hint:

sketch_jul22a.ino: In function 'void setup()':
sketch_jul22a.ino:7:31: warning: suggest parentheses around comparison in operand of '&' [-Wparentheses]
if (0B00000010 & 0B00000010 == 0B00000010)
~^~~

That means:
(0B00000010 & 0B00000010 == 0B00000010)
is interpreted as
(0B00000010 & (0B00000010 == 0B00000010))
which is 'false':

(0B00000010 & (0B00000010 == 0B00000010))
(0B00000010 & true)
(0B00000010 & 0B00000001)
(0B00000000)
(false)

Wow, thank you! That was driving me nuts.
I’ll have my compiler warnings turned all the way up from now on.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.