Day 6/30 : Bit Manipulation Techniques In C
1. Core Bitwise Operators
AND (): Sets bits to 1 only if both bits are 1.
OR (): Sets bits to 1 if either bit is 1.
XOR (): Sets bits to 1 if bits differ.
NOT (): Flips all bits (unary operator).
Left Shift (): Shifts bits left, padding with 0s.
Right Shift (): Shifts bits right (padding depends on sign).
2. Essential Techniques
Set a Bit:
num |= (1 << n); // Set nth bit
Clear a Bit:
num &= ~(1 << n); // Clear nth bit
Toggle a Bit:
num ^= (1 << n); // Toggle nth bit
Check a Bit:
if (num & (1 << n)) // Check if nth bit is set
Modify Multiple Bits:
num = (num & ~0x0F) | 0xA; // Set lower 4 bits to 1010
3. Advanced Operations
Swap Values (without temp):
a ^= b;
b ^= a;
a ^= b;
Check Even/Odd:
if (num & 1) // Odd if true
Count Set Bits:
int count = 0;
while (num) {
num &= (num - 1); // Clear the least significant set bit
count++;
}
Isolate Rightmost 1:
rightmost = num & -num;
4. Bitmasks & Shifts
Extract Bits:
unsigned extract = (num >> offset) & mask;
Rotate Bits (left by ):
result = (num << n) | (num >> (sizeof(num)*8 - n));
5. Best Practices
Use types to avoid sign-extension issues.
Avoid undefined behavior: Don’t shift by bit width (e.g., for ).
Use parentheses for clarity: ≠ .
Preprocessor helpers:
#define BIT_SET(num, n) ((num) |= (1U << (n)))
#define BIT_CLEAR(num, n) ((num) &= ~(1U << (n)))
Example: Bitwise Functions
Key Takeaways:
Bit manipulation enables efficient low-level control.
Crucial for embedded systems, cryptography, and performance-critical code.
Always document bitwise operations for readability.