Bitwise AND &
What you'll learn: How to use the bitwise AND operator to compare individual bits and "filter" data at the binary level.
Thinking Like a Computer
Computers don't see the number 5; they see 0101. Bitwise operators allow you to reach inside a variable and manipulate these individual switches. The Bitwise AND operator, represented by a single ampersand &, compares two numbers bit by bit.
Think of it like a security gate with two locks. For the gate to open (resulting in a 1), both keys must be turned (both bits must be 1). If either key is missing, or if both are missing, the gate stays locked (resulting in a 0).
The Truth Table
When the computer compares two bits using &, it follows these strict rules:
1 & 1= 1 (Both are true)1 & 0= 0 (One is false)0 & 1= 0 (One is false)0 & 0= 0 (Both are false)
A Concrete Example
Imagine you have two numbers, 12 and 10. Let’s see what happens when we use 12 & 10. First, we convert them to 4-bit binary:
- 12 is
1100 - 10 is
1010
Now, we line them up and compare each column:
1 1 0 0 (12)
& 1 0 1 0 (10)
-----------
1 0 0 0 (Result is 8)
In the first column, both are 1, so the result is 1. In every other column, there is at least one 0, so the result is 0. The binary result 1000 is the number 8 in decimal.
Why Use This?
The most common use for & is masking. Imagine you have a byte representing eight different light switches in a house. If you only care if the third switch is on, you can "mask" the others by ANDing the whole byte with a number that only has a 1 in the third position. This turns all other irrelevant bits to 0, leaving you only with the information you need.
#include <stdio.h>
int main() {
int myLights = 12; // Binary: 1100
int mask = 8; // Binary: 1000
// Check if the 4th bit is "on"
int result = myLights & mask;
printf("The result of 12 & 8 is: %d\n", result);
// Output: 8 (which means the bit was indeed set)
return 0;
}
Key takeaway
The bitwise & operator returns a 1 only if both compared bits are 1, making it perfect for extracting specific bits from a value.