β‘ Bit Manipulation β Comprehensive Study Guide
**Bit Manipulation** is a technique used to perform operations at the **bit level**. It is widely used in **competitive programming, encryption, networking, and optimizing algorithms**.
π Why is Bit Manipulation Important?
- π **Faster Computation** β Performs **operations in O(1) time**.
- β‘ **Memory Efficient** β Uses **less space** compared to integer operations.
- π’ **Used in Low-Level Programming** β Involves direct **hardware interaction**.
- π‘ **Efficient in Cryptography & Networking** β Used in **data encryption** & **checksum calculations**.
π’ Understanding Binary Representation
Every number in a computer is stored in **binary form (0s and 1s)**. Example:
Decimal: 5 β Binary: 101
Decimal: 10 β Binary: 1010
π οΈ Common Bitwise Operators
Operator | Symbol | Description | Example (5 & 3) |
---|---|---|---|
AND | & | Returns 1 if both bits are 1 | 101 & 011 = 001 (1) |
OR | | | Returns 1 if at least one bit is 1 | 101 | 011 = 111 (7) |
XOR | ^ | Returns 1 if the bits are different | 101 ^ 011 = 110 (6) |
NOT | ~ | Flips all bits | ~5 = -6 (in 2βs complement) |
Left Shift | << | Shifts bits to the left (multiplies by 2) | 5 << 1 = 10 |
Right Shift | >> | Shifts bits to the right (divides by 2) | 5 >> 1 = 2 |
β‘ Important Bit Manipulation Tricks
β 1. Check if a Number is Even or Odd
Use the **AND operator**:
bool isEven(int n) {
return (n & 1) == 0; // If last bit is 0, the number is even
}
β 2. Check if a Number is a Power of 2
Only **one bit** is set in powers of 2.
bool isPowerOfTwo(int n) {
return (n & (n - 1)) == 0 && n > 0;
}
β 3. Count the Number of 1s in Binary (Hamming Weight)
Uses Brian Kernighanβs Algorithm.
int countSetBits(int n) {
int count = 0;
while (n) {
n = n & (n - 1); // Removes the rightmost set bit
count++;
}
return count;
}
β 4. Reverse Bits of a Number
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n = n >> 1;
}
return result;
}
β 5. Swap Two Numbers Without Using a Third Variable
void swap(int &a, int &b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
β³ Time Complexity Analysis
Operation | Time Complexity |
---|---|
Bitwise AND, OR, XOR | O(1) |
Checking Even/Odd | O(1) |
Finding Power of 2 | O(1) |
Counting Set Bits | O(log n) |
Reversing Bits | O(32) = O(1) |
π Real-World Applications of Bit Manipulation
- π‘ **Network Protocols** β Bitwise operations in **IP addresses & compression.**
- π **Cryptography** β Encrypting & decrypting data using bit operations.
- β‘ **Graphics & Game Development** β Efficient color manipulation & animations.
- π **Stock Market Analysis** β Storing data in compact form.
- π₯οΈ **Operating Systems & Hardware** β CPU registers, cache optimization.