Bitwise AND (&) operator
Bitwise AND (&) operator will take two equal length binary sequence and perform the bitwise AND operation on each pair of bit sequence.
AND operator will return 1, if both bits are 1.
Otherwise it will return 0.
The truth table,
Ai |
Bi |
A i& Bi |
---|---|---|
0 |
0 |
0 |
0 |
1 |
0 |
1 |
0 |
0 |
1 |
1 |
1 |
Example
Let’s take two integers,
A = 5 and B = 9.
Then what will be the result of A & B?
Let’s represent each number in binary format.
A = (0101) 2
B= (1001) 2
Now, apply the bitwise AND logic in each pair of corresponding bits.
Like,
Pictorial Explanation
So, A&B will be (0001)2, which is 1.
What is the use of bitwise AND (&) operator ?
Let’s continue the previously discussed example where the sensor will update direction status in car robot.
In order to trun the car to the specified direction, we need to check which direction bit is enabled.
Let's assume that sensor updates the right direction bit as ON.
Then the sensor status will be 0001. (backward 0, forward 0, left 0, right 1).
How will you check whether the first bit (right direction) is ON or OFF?
Using bitwise AND operator, we can check the particular bit has enabled(set to 1) or disabled(set to 0).
To check the bit status, we need to create a binary AND MASK.
AND MASK should have only one 1 in some position where we supposed to check the bit status.
And it should have the remaining bits as 0.
Example
Here, we are going to check the first bit status.
So, MASK will be 0001 (1 in first bit and remaining 3 bits are zero).
Now calculate Sensor status & MASK
Like,
Sensor status                  = 0001
MASK                             = 0001
Sensor status & MASK      = 0001
The answer is 1 which indicates that the car should change it's direction to the right.
Similarly, let's check for left direction status which is second bit.
MASK will be 0010 (left 1, remaining are zero)
Now, calculate Sensor status & MASK
Sensor status                  = 0001
MASK                             = 0010
Sensor status & MASK      = 0000
Now the answer is 0 which indicates don’t trun the car to the left direction.