When to Use Bitwise Operators in C
Bitwise operators (&, |, ^, ~, <<, >>) shine in 7 specific scenarios where bit-level control is needed.
Faster than arithmetic, memory-efficient, embedded systems essential.
1. Flags & Permissions (Most Common)
C
User permission flags
#define READ 1 // 0001
#define WRITE 2 // 0010
#define EXEC 4 // 0100
int user = READ | WRITE; // 0011
if (user & READ) // Check flag
printf("Can read\n");
One integer holds multiple boolean flags.
2. Bit Masks
C
Clear/set specific bits
int flags = 0b1111;
// Clear bit 2 (4)
flags &= ~4; // 0b1011
// Set bit 1 (2)
flags |= 2; // 0b1111
// Toggle bit 0
flags ^= 1; // 0b1110
3. Fast Math (Powers of 2)
C
Shift = multiply/divide by 2^n
int x = 10;
x << 2; // x*4 = 40
x >> 1; // x/2 = 5
// Instead of: x *= 4; x /= 2;
Faster than multiplication/division.
4. Embedded Systems & Hardware
C
Control GPIO pins
#define LED_PIN 0x01
#define RELAY_PIN 0x02
PORTB |= LED_PIN; // Turn ON LED
PORTB &= ~RELAY_PIN; // Turn OFF relay
5. Swap Without Temp Variable
C
XOR swap trick
int a = 5, b = 3;
a ^= b; // a=6, b=3
b ^= a; // a=6, b=5
a ^= b; // a=3, b=5
// Swapped!
6. Isolate/Extract Bits
C
Extract specific bits
int packed = 0b10110110;
// Get bit 3 (8)
int bit3 = (packed & 8) != 0;
// Get bits 2-0 (6)
int low3 = packed & 0b111;
7. Network Protocols
C
Protocol flags
#define TCP_FIN 0x01
#define TCP_SYN 0x02
#define TCP_RST 0x04
if (flags & TCP_SYN)
printf("SYN packet\n");
When NOT to Use
- Never in if conditions (use &&/||)
- Never for boolean logic
- Complex math (use arithmetic)
Conclusion
Bitwise = compact data + speed. Perfect for flags, hardware, optimization.
Master these 7 cases and you'll write efficient C code.
Codecrown