C Bitwise Operators
Bitwise operators work on single bits inside a number. They are not the same as the logical operators, which work on whole true-or-false values.
AND and OR
12 and 10 share only the 8 bit, so 12 & 10 is 8. Either bit is 1 in the 8, 4, and 2 places, so 12 | 10 is 14.
#include <stdio.h>
int main() {
int a = 12;
int b = 10;
printf("%d\n", a & b);
printf("%d\n", a | b);
return 0;
}XOR picks differences
12 and 10 differ in the 4 and 2 places, so 12 ^ 10 is 6. The bits that match give 0.
#include <stdio.h>
int main() {
printf("%d\n", 12 ^ 10);
return 0;
}Shift left and right
Moving 3 left by 2 bits doubles it twice, so 3 << 2 is 12. Moving 12 right by 2 bits halves it twice, so 12 >> 2 is 3.
#include <stdio.h>
int main() {
printf("%d\n", 3 << 2);
printf("%d\n", 12 >> 2);
return 0;
}Example
#include <stdio.h>
int main() {
int a = 5;
int b = 3;
printf("5 & 3 = %d\n", a & b);
printf("5 | 3 = %d\n", a | b);
printf("5 ^ 3 = %d\n", a ^ b);
printf("5 << 1 = %d\n", a << 1);
printf("5 >> 1 = %d\n", a >> 1);
return 0;
}Key points
- A bit is one 0 or 1 held inside a number.
- The & operator compares two numbers bit by bit and keeps a 1 only where both bits are 1.
- The | operator keeps a 1 where either bit is 1.
- The ^ operator keeps a 1 where the two bits differ.
- The << operator moves bits left, which doubles the value for each step.
- The >> operator moves bits right, which halves the value for each step.
5 and 3 share only the 1 bit, so 5 & 3 is 1. Together they cover the 4, 2, and 1 bits, so 5 | 3 is 7. They differ in the 4 and 2 places, so 5 ^ 3 is 6. Shifting 5 left once gives 10, and shifting it right once gives 2.
Note
& is bitwise and, while && is logical and. They answer different questions.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is 6 & 3?