Bitwise operators perform operations on individual bits of integers. Here's a detailed explanation of each:
int a = 5, b = 3;
printf("%d", a & b); // Output: 1
Compares bits of a and b. Returns 1 only if both bits are 1.
| a (5) | b (3) | a & b |
|---|---|---|
| 0101 | 0011 | 0001 (1) |
int a = 5, b = 3;
printf("%d", a | b); // Output: 7
Compares bits of a and b. Returns 1 if either bit is 1.
| a (5) | b (3) | a | b |
|---|---|---|
| 0101 | 0011 | 0111 (7) |
int a = 5, b = 3;
printf("%d", a ^ b); // Output: 6
Compares bits of a and b. Returns 1 if bits are different.
| a (5) | b (3) | a ^ b |
|---|---|---|
| 0101 | 0011 | 0110 (6) |
int a = 5;
printf("%d", ~a); // Output: -6
Inverts all bits of the number.
In 32-bit systems: ~00000000 00000000 00000000 00000101 = 11111111 11111111 11111111 11111010
This represents -6 in 2’s complement form.
int a = 5;
printf("%d", a << 1); // Output: 10
Shifts all bits to the left by the specified number of positions.
0101 << 1 becomes 1010 → 10
Each left shift is equivalent to multiplying by 2.
int a = 5;
printf("%d", a >> 1); // Output: 2
Shifts all bits to the right by the specified number of positions.
0101 >> 1 becomes 0010 → 2
Each right shift is equivalent to dividing by 2 (ignoring remainder).