# Can someone explain bitwise AND to me please?

Discussion in 'OT Technology' started by MSTRBKR, May 17, 2009.

1. ### MSTRBKRNew Member

Joined:
Dec 18, 2007
Messages:
7,584
0
Location:
Cydonia
((value & (1 << 1)) == 0)

I know the truth table in logic looks like this:

A B A.B
0 0 0
0 1 0
1 0 0
1 1 1

If value is 1 and 1 << 1 is 2, what does 1 ANDed with 2 equal?

My first thought was that both need to be equal for the output to be 1 i.e. value would need to be 2 but in the context of the entire program it makes no sense.

Joined:
Jan 16, 2003
Messages:
10,760
3
Location:
Plantation, FL
itd be 0. write the numbers out in binary bits

1 = 0 0 0 0 0 0 0 1
2 = 0 0 0 0 0 0 1 0

for two AND'd bits to be 1 both must equal 1. if one is 1 and one is 0 then you get 0. So ANDing all these bits together = 0.

Joined:
Jan 16, 2003
Messages:
10,760
3
Location:
Plantation, FL
4. ### MSTRBKRNew Member

Joined:
Dec 18, 2007
Messages:
7,584
0
Location:
Cydonia
Okay that's what I thought.

So if it was 3 & 2?

000011
000010

000010

The result would be 2.

The piece of code is:

Code:
```
if ((Value & (1 << 0)) == 0)
PORTA = 0;
else
PORTA = 0b010000;
TRISA = 0b001111;
```
So if the result was 2, else would execute correct?

Don't worry about the PORTA and TRISA, I understand all that

Cheers man, helped me out and that link is awesome!!

5. ### MSTRBKRNew Member

Joined:
Dec 18, 2007
Messages:
7,584
0
Location:
Cydonia
Sorry it wasn't what I thought, I had thought about it possibly being done that way but wasn't sure.

Either way, the program makes sense now.

Joined:
Jan 16, 2003
Messages:
10,760
3
Location:
Plantation, FL
that piece of code is checking to see if the least significant bit is set. essentially if Value is an even number then PORTA = 0 will happen. if Value is odd then the else occurs. is this C/C++?

7. ### MSTRBKRNew Member

Joined:
Dec 18, 2007
Messages:
7,584
0
Location:
Cydonia
C

It's part of a program that is loaded onto a PIC16F684 that flashes 4 bipolar LEDs extremely fast to give the apperance that all 8 colours are on simultaneously.

Joined:
Jan 16, 2003
Messages:
10,760
3
Location:
Plantation, FL
ok because of the code formatting i think theres an error with:
TRISA = 0b001111;

because that is going to get assigned regardless of the condition.

if you want both of those to only happen in the else you need

else
{
PORTA = 0b010000;
TRISA = 0b001111;
}

9. ### MSTRBKRNew Member

Joined:
Dec 18, 2007
Messages:
7,584
0
Location:
Cydonia
Oh don't worry about that, that all works. Just wanted to know about the & stuff.

Joined:
Dec 18, 2007
Messages:
7,584