Bitwise Operators in C
Bitwise operators work directly on the **bits** (0s and 1s) of integers. They are extremely fast and widely used in low-level programming, embedded systems, graphics, cryptography, and optimization.
• Operate on **integer types** only (char, short, int, long, etc.)
• Very fast (single CPU instruction)
• Common in flags, masks, bit fields, packing/unpacking data
• Very fast (single CPU instruction)
• Common in flags, masks, bit fields, packing/unpacking data
All 6 Bitwise Operators in C
| Operator | Symbol | Description | Common Use Cases |
|---|---|---|---|
| Bitwise AND | & | 1 only if both bits are 1 | Clear bits, check flags, masks |
| Bitwise OR | | | 1 if at least one bit is 1 | Set bits, combine flags |
| Bitwise XOR | ^ | 1 if bits are different | Toggle bits, find unique, swap without temp |
| Bitwise NOT | ~ | Flip all bits (1→0, 0→1) | One’s complement, invert mask |
| Left Shift | << | Shift bits left (multiply by 2ⁿ) | Fast multiply, bit packing |
| Right Shift | >> | Shift bits right (divide by 2ⁿ) | Fast divide, extract bits |
Truth Tables (AND, OR, XOR)
| A | B | A & B | A | B | A ^ B |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
Note: ~A (NOT) is simply the opposite of A
Practical Examples & Tricks
1. Check if number is even/odd
C
if (n & 1) // odd
printf("Odd");
else // even
printf("Even");
2. Set, Clear, Toggle, Check a bit
C
// Set bit at position pos (0-based)
n |= (1 << pos);
// Clear bit
n &= ~(1 << pos);
// Toggle bit
n ^= (1 << pos);
// Check if bit is set
if (n & (1 << pos)) printf("Bit is ON");
3. Swap two numbers without temporary variable
C
a = a ^ b;
b = a ^ b;
a = a ^ b;
4. Fast multiply & divide by power of 2
C
x << 3 // x * 8
x >> 2 // x / 4
5. Extract lower/upper nibble
C
lower_nibble = n & 0x0F;
upper_nibble = (n >> 4) & 0x0F;
Useful Bit Masks (Hex)
| Mask | Hex | Binary |
|---|---|---|
| 0xFF | 11111111 | Last 8 bits (1 byte) |
| 0x0F | 00001111 | Lower nibble |
| 0xF0 | 11110000 | Upper nibble |
| 0x01 | 00000001 | Check LSB (odd/even) |
| 0x80000000 | 1000...0 | Check sign bit (32-bit) |
Important Notes & Warnings
- Right shift (>>) on signed integers is implementation-defined (arithmetic vs logical)
- Use unsigned types when doing bit manipulation for predictable behavior
- ~ operator flips all bits (including higher bits) → careful with signed integers
- Always use parentheses with shifts: `(1 << pos)`
Codecrown