Bitwise Operators in CPP

1 min read

Bitwise operators manipulate individual bits of integers at the binary level. They are blazingly fast because they map directly to CPU instructions.
Operator | Example | ||
& (AND) | a & b | ||
(OR) | a | b | |
^ (XOR) | a ^ b | ||
~ (NOT) | ~a | ||
<< (LEFT SHIFT) | a << n | ||
\>> (RIGHT SHIFT) | a >> n |
🎨 The Art of Bit Manipulation 0️⃣1️⃣
Swap Variables Without a Temporary
int a = 5, b = 7;
a = a ^ b; // a = 5 ^ 7 = 2
b = b ^ a; // b = 7 ^ 2 = 5
a = a ^ b; // a = 2 ^ 5 = 7
Check Even/Odd Instantly
bool isEven(int num) {
return (num & 1) == 0; // Even if the last bit is 0
}
Fast Multiplication/Division by Powers of 2
int x = 10;
x = x << 3; // 10 * 8 = 80
x = x >> 2; // 80 / 4 = 20
0
Subscribe to my newsletter
Read articles from Om Bhandwalkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
