C Bitwise Operators
Bitwise operators work on the individual bits of integers: & (and), | (or), ^ (xor), ~ (not), << and >> (shift). They are used for flags, masks and low-level protocols.
ExampleC
#include <stdio.h>
int main(void) {
unsigned int a = 12; // 1100
unsigned int b = 10; // 1010
printf("%u\n", a & b); // 8 (1000)
printf("%u\n", a | b); // 14 (1110)
printf("%u\n", a ^ b); // 6 (0110)
printf("%u\n", a << 2); // 48
printf("%u\n", a >> 1); // 6
unsigned int flags = 0;
flags |= 1 << 0; // set bit 0
flags |= 1 << 3; // set bit 3
printf("flags=%u\n", flags);
printf("bit 3 set? %d\n", (flags & (1 << 3)) != 0);
flags &= ~(1 << 0); // clear bit 0
printf("flags=%u\n", flags);
return 0;
}Output
8 14 6 48 6 flags=9 bit 3 set? 1 flags=8
Quick check
What does x << 2 do to an integer?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.