C Bitwise Operators – Direct Manipulation of Bits
Bitwise operators in C allow you to manipulate individual bits of data directly. They’re especially useful in systems programming, embedded systems, game development, and performance-critical applications.
Why Use Bitwise Operators?
Bitwise operators:
Perform operations faster than arithmetic.
Help in flags, masks, compression, and encryption.
Give low-level control over data and memory.
List of Bitwise Operators in C
Operator | Name | Description |
---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 |
` | ` | OR |
^ | XOR | Sets each bit to 1 if only one is 1 |
~ | NOT | Inverts all the bits |
<< | Left Shift | Shifts bits left, filling with 0 on the right |
>> | Right Shift | Shifts bits right, preserving sign on left |
Bitwise AND (&)
int a = 5; // 0101
int b = 3; // 0011
int result = a & b; // 0001 → 1
Bitwise OR (|)
int a = 5; // 0101
int b = 3; // 0011
int result = a | b; // 0111 → 7
Bitwise NOT (~)
int a = 5; // 0101
int result = ~a; // 1010 → -6 (in 2's complement for 4 bits)
Left Shift (<<)
int a = 3; // 0011
int result = a << 2; // 1100 → 12
Right Shift (>>)
int a = 12; // 1100
int result = a >> 2; // 0011 → 3
Complete Code Example
#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("a & b = %d\n", a & b); // AND
printf("a | b = %d\n", a | b); // OR
printf("a ^ b = %d\n", a ^ b); // XOR
printf("~a = %d\n", ~a); // NOT
printf("a << 1 = %d\n", a << 1); // Left Shift
printf("a >> 1 = %d\n", a >> 1); // Right Shift
return 0;
}
Output:
a & b = 1
a | b = 7
a ^ b = 6
~a = -6
a << 1 = 10
a >> 1 = 2
Best Practices
Tip | Why it Matters |
---|---|
Use with unsigned for clarity | Avoids sign-related issues with shifts |
Use masks with & and ` | ` |
Avoid unnecessary shifting large values | Can lead to undefined behavior |
Common Mistakes
Mistake | Problem |
---|---|
Using signed int with shifts | May cause unexpected results |
Forgetting parentheses | Bitwise has lower precedence than comparison |
Misunderstanding ~a | Returns 2’s complement, not just flipped bits |