You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Pack/Unpack colors - Plain Englishuint32_t color = (r << 16) | (g << 8) | b; // "Combine R, G, B into one number"uint8_t red = (color >> 16) & 0xFF; // "Extract red component"uint8_t green = (color >> 8) & 0xFF; // "Extract green component"uint8_t blue = color & 0xFF; // "Extract blue component"// Manipulate colors
color &= 0xFF00FF; // "Remove green channel"
color |= (128 << 8); // "Set green to 128"
color ^= 0xFFFFFF; // "Invert all colors"
Subset/Combination Generation
// Iterate through all subsets - Plain Englishfor (int subset = 0; subset < (1 << n); subset++) {
// Each bit position represents include/exclude for element// "Try all possible combinations"
}
// Iterate through all subsets of a setint set = 0b1101; // Original setfor (int subset = set; subset > 0; subset = (subset - 1) & set) {
// "Visit each valid subset"
}
Regular arithmetic (compiler optimizes x * 8 → x << 3)
Premature optimization
When readability is more important than nano-optimization
Type Safety Tips
// GOOD: Use unsigned types for bit manipulationuint32_t flags = 0;
flags |= (1U << 15); // Safe// BAD: Signed types can cause undefined behaviorint flags = 0;
flags |= (1 << 31); // Undefined behavior!// GOOD: Use fixed-width types for portabilityuint32_t mask = 0xFF00FF00; // Always 32 bits// BAD: int size varies by platformunsignedint mask = 0xFF00FF00; // Could be 16, 32, or 64 bits
Quick Reference - What Each Operation Does to Numbers
Operation
Effect on Number
Example
n << 1
Multiply by 2
5 << 1 = 10
n >> 1
Divide by 2
10 >> 1 = 5
n & (n-1)
Remove lowest set bit
12 & 11 = 8 (1100 & 1011 = 1000)
n & -n
Isolate lowest set bit
12 & -12 = 4 (1100 & ...10100 = 0100)
n | (n+1)
Set lowest unset bit
10 | 11 = 11 (1010 | 1011 = 1011)
n ^ (n+1)
Get mask of trailing zeros + 1
8 ^ 9 = 1 (1000 ^ 1001 = 0001)
Memory Alignment & Structure Packing
// Check alignment - Plain Englishbool is_aligned = (address & (alignment - 1)) == 0; // "Is address aligned to boundary?"// Round up to alignmentsize_t aligned = (size + align - 1) & ~(align - 1); // "Round up to next alignment"// Extract bit fieldsstructPacket {
uint16_t data;
// Extract fields using masks and shiftsuint8_tgetType() { return (data >> 12) & 0x0F; } // "Get bits 12-15"uint8_tgetFlags() { return (data >> 8) & 0x0F; } // "Get bits 8-11"uint8_tgetValue() { return data & 0xFF; } // "Get bits 0-7"
};
Remember: Bitwise operations work on the binary representation of numbers. Think of each number as a row of switches (bits) that can be ON (1) or OFF (0). These operations let you manipulate those switches directly and efficiently.