bitwise
bitwise
Bitwise operators work on individual bits of integer data types. They're fundamental for low-
level programming, optimization, and bit manipulation.
Truth Table:
A|B|A&B
--|---|------
0|0| 0
0|1| 0
1|0| 0
1|1| 1
Example:
Common Uses:
// Check if even
if ((num & 1) == 0) {
2. Bitwise OR (|)
Truth Table:
A|B|A|B
--|---|------
0|0| 0
0|1| 1
1|0| 1
1|1| 1
Example:
Common Uses:
// Combine flags
A|B|A^B
--|---|------
0|0| 0
0|1| 1
1|0| 1
1|1| 0
Example:
Common Uses:
a ^= b;
b ^= a;
a ^= b;
// Simple encryption/decryption
Example:
Common Uses:
Example:
Common Uses:
Create bit masks: 1 << n creates mask with only nth bit set
// Multiply by 8 (2^3)
Two Types:
Example:
int b = -20;
Common Uses:
E icient algorithms
// Divide by 4 (2^2)
a |= b; // Equivalent to: a = a | b
a ^= b; // Equivalent to: a = a ^ b
}
// Toggle nth bit
int count = 0;
while (num) {
num >>= 1;
return count;
// Define flags
// Set flags
int permissions = 0;
permissions |= FLAG_READ;
permissions |= FLAG_WRITE;
// Remove flag
// Toggle flag
permissions ^= FLAG_EXECUTE;
int packed;
};
Performance Considerations
o x << 1 instead of x * 2
o x >> 1 instead of x / 2
o x & 1 instead of x % 2
4. Use unsigned types for pure bit manipulation to avoid unexpected behavior
Common Pitfalls
3. if (a + b & c == 0)
4.
6. if ((a + b) & c == 0)
8. int a = 5;
11. Signed integer overflow during shifts can cause undefined behavior
Advanced Techniques
int countSetBits(int n) {
int count = 0;
while (n) {
count++;
return count;
if (exp & 1) {
result *= base;
base *= base;
exp >>= 1;
return result;
Bitwise operations are powerful tools for e icient programming, especially in systems
programming, embedded development, and competitive programming. Master these
fundamentals and you'll have a solid foundation for advanced bit manipulation techniques!