Bit Manipulation Algorithms

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.

1. Why Learn Bit Tricks?

2. Daily Life Analogy

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.

3. Common Bit Operators

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

4. Set a Bit

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)

5. Clear a Bit

Turn a bit OFF at a position.


int n = 5; // 0101
int pos = 2;
n = n & ~(1 << pos);
  

New value = 1 (0001)

6. Toggle a Bit

Flip a bit at a position.


int n = 5; // 0101
int pos = 0;
n = n ^ (1 << pos); // toggle bit
  

New value = 4 (0100)

7. Check if Bit is Set

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

8. Count Set Bits

How many 1s in the number?


int count = 0;
int n = 13; // 1101
while (n != 0) {
  count += n & 1;
  n = n >> 1;
}
  

Answer = 3

9. Is Number Power of Two?

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

10. Swap Numbers Without Temp


int a = 5, b = 7;
a = a ^ b;
b = a ^ b;
a = a ^ b;
  

a = 7, b = 5 (Swapped!)

11. Applications in Real Life

Summary

Fun Fact

A 32-bit number can store 32 yes/no answers. You can track 32 settings using just 1 number!