Computers use bits. A bit is a 0 or 1. All data is stored as bits.
Bit manipulation means changing or checking bits using special operations.
These operations are fast and powerful.
Think of a bit as a light switch. 0 means off, 1 means on.
You can turn it on, turn it off, or flip it.
Just like you control lights in a room.
Operator | Symbol | Example |
---|---|---|
AND | & |
5 & 3 = 1 |
OR | | |
5 | 3 = 7 |
XOR (exclusive OR) | ^ |
5 ^ 3 = 6 |
NOT | ~ |
~5 = -6 |
Left Shift | << |
5 << 1 = 10 |
Right Shift | >> |
5 >> 1 = 2 |
Note: 5 in binary = 101, 3 = 011
Turn a bit ON at a position.
int n = 5; // 0101
int pos = 1;
n = n | (1 << pos); // sets bit at pos
New value = 7 (0111)
Turn a bit OFF at a position.
int n = 5; // 0101
int pos = 2;
n = n & ~(1 << pos);
New value = 1 (0001)
Flip a bit at a position.
int n = 5; // 0101
int pos = 0;
n = n ^ (1 << pos); // toggle bit
New value = 4 (0100)
See if a bit is ON.
int n = 5;
int pos = 2;
bool isSet = (n & (1 << pos)) != 0;
True, because bit 2 is ON in 101
How many 1s in the number?
int count = 0;
int n = 13; // 1101
while (n != 0) {
count += n & 1;
n = n >> 1;
}
Answer = 3
Only one bit is set in power of 2.
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
8 → 1000, 7 → 0111 → AND = 0 → true
int a = 5, b = 7;
a = a ^ b;
b = a ^ b;
a = a ^ b;
a = 7, b = 5 (Swapped!)
A 32-bit number can store 32 yes/no answers. You can track 32 settings using just 1 number!