Introduction to Bit Manipulation
Bit manipulation involves directly working with individual bits in binary representations of numbers. It’s essential for low-level programming, optimization, and working with hardware.Bitwise Operators
Basic Operators
| Operator | Name | Description | Example |
|---|---|---|---|
& | AND | Both bits must be 1 | 5 & 3 = 1 |
| | OR | At least one bit must be 1 | 5 | 3 = 7 |
^ | XOR | Bits must be different | 5 ^ 3 = 6 |
~ | NOT | Inverts all bits | ~5 = -6 |
<< | Left shift | Shift bits left | 5 << 1 = 10 |
>> | Right shift | Shift bits right | 5 >> 1 = 2 |
Visual Examples
Converting Binary to Unsigned Int
From0-binary_to_uint.c:
Algorithm: This uses the property that reading binary left-to-right is like:
- Multiply current result by 2 (shift left)
- Add the current bit (0 or 1)
Printing Binary Representation
From1-print_binary.c:
- Recursive approach: Process bits from left to right
- Base case:
n >> 1is 0 (no more bits) - Extract bit:
n & 1gets the rightmost bit - Convert to char:
+ '0'converts 0/1 to ‘0’/‘1’
print_binary(5):
Getting a Specific Bit
From2-get_bit.c:
- Create mask:
1 << indexputs 1 in the desired position - Apply mask:
n & maskisolates that bit - Shift back:
>> indexmoves bit to position 0
Setting a Bit to 1
From3-set_bit.c:
- Validate index: Check if index is within valid range (0-63 for 64-bit)
- Create mask:
1 << indexcreates mask with 1 at position - OR operation:
*n | masksets the bit to 1
Clearing a Bit (Set to 0)
From4-clear_bit.c:
- Create inverted mask:
~(1 << index)creates mask with 0 at position, 1s elsewhere - AND operation:
*n & maskclears the bit
Counting Bits to Flip
From5-flip_bits.c:
- XOR operation:
n ^ mproduces 1 where bits differ - Count ones: Loop counts the 1 bits in the XOR result
flip_bits(5, 3)
Why XOR? XOR produces 1 when bits are different:
- 0 ^ 0 = 0 (same)
- 1 ^ 1 = 0 (same)
- 0 ^ 1 = 1 (different)
- 1 ^ 0 = 1 (different)
n ^ m highlights exactly which bits need to change!Common Bit Manipulation Patterns
Check if Bit is Set
Toggle a Bit
Check if Number is Power of 2
Count Set Bits (Population Count)
Swap Two Numbers Without Temp
Get Rightmost Set Bit
Clear Rightmost Set Bit
Bit Masks and Flags
Using Flags
Packing Multiple Values
Performance Considerations
Faster Operations
- Multiply by 2:
n << 1faster thann * 2 - Divide by 2:
n >> 1faster thann / 2 - Check even/odd:
n & 1faster thann % 2 - Clear low bits:
n & ~maskefficient
Use Cases
- Hardware register manipulation
- Network protocol parsing
- Compression algorithms
- Cryptographic operations
Best Practices
-
Use meaningful constants
-
Comment bit operations
-
Validate index ranges
-
Use unsigned for bit operations
-
Be careful with negative numbers
Common Mistakes
Forgetting Operator Precedence
Mixing Signed and Unsigned
Using >> for Division by 2 with Negatives
Key Takeaways
- Bitwise operators work directly on binary representation
- Use
&for masking/testing,|for setting,^for toggling - Shifts are efficient multiply/divide by powers of 2
- XOR useful for comparing, swapping, and encryption
- Always validate index ranges when accessing specific bits
- Use unsigned types for bit manipulation
- Bit operations are essential for low-level programming
Related Topics
Preprocessor
Use macros for bit manipulation patterns
Structures & Typedef
Combine with bit fields in structures