BIT MANIPULATION TRICKS IN C
Essential Bit Manipulation Tricks
| # | Trick | Description |
|---|---|---|
| 1 | Check if number is even/odd | Use (num & 1) - returns 1 for odd, 0 for even |
| 2 | Test if n-th bit is set | Use (num & (1 << n)) - non-zero means set |
| 3 | Set n-th bit | Use num | (1 << n) to set specific bit |
| 4 | Unset n-th bit | Use num & ~(1 << n) to clear specific bit |
| 5 | Toggle n-th bit | Use num ^ (1 << n) to flip specific bit |
| 6 | Turn off rightmost set bit | Use num & (num - 1) |
| 7 | Isolate rightmost set bit | Use num & -num |
| 8 | Right propagate rightmost set bit | Use num | (num - 1) |
| 9 | Count set bits (popcount) | Use __builtin_popcount() or manual counting |
| 10 | Swap two numbers | Use XOR: a ^= b; b ^= a; a ^= b; |
| 11 | Check power of 2 | Use (num & (num - 1)) == 0 |
| 12 | Absolute value without branching | Use mask = num >> 31; (num + mask) ^ mask; |
| 13 | Find log2 of a number | Count leading zeros or use bit scanning |
| 14 | Reverse bits of a number | Use lookup table or bit-by-bit reversal |
| 15 | Find next power of 2 | Use --num; num |= num >> 1; num |= num >> 2; etc. |
Implementation Examples
Basic Bit Operations
// Set, clear, toggle, check bits
unsigned int num = 0;
// Set 3rd bit
num |= (1 << 3);
// Clear 2nd bit
num &= ~(1 << 2);
// Toggle 5th bit
num ^= (1 << 5);
// Check if 4th bit is set
if (num & (1 << 4)) {
printf("Bit 4 is set\n");
}
Count Set Bits
// Count number of 1 bits (popcount)
int countSetBits(unsigned int n) {
int count = 0;
while (n) {
n &= (n - 1); // clears least significant set bit
count++;
}
return count;
}
// Built-in version (GCC)
int builtinCount = __builtin_popcount(n);
Swap Without Temp
// Swap two numbers without temp
void swap(int *a, int *b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
// Alternative method
void swapAdd(int *a, int *b) {
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
Fast Power of 2 Check
// Check if number is power of 2
int isPowerOfTwo(unsigned int n) {
return n && !(n & (n - 1));
}
// Get next power of 2
unsigned int nextPowerOf2(unsigned int n) {
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
Pro Tips for Bit Manipulation
Remember: Bitwise operations have lower precedence than arithmetic operations! Use parentheses liberally.
Safety Practices
- Be aware of integer promotion rules
- Use unsigned types for bit manipulation
- Watch out for sign bit in right shifts (use unsigned)
- Document complex bit operations with comments
Performance Tips
- Bit operations are among the fastest CPU operations
- Use bit fields for compact data storage
- Lookup tables can speed up complex bit operations
- Compiler intrinsics (like __builtin_popcount) are highly optimized
Related Resources
Related Bit Manipulation Resources