Practical Bit Tricks
Common techniques.
Useful Bit Tricks
Once you understand bitwise operators, a set of compact tricks becomes available. They are fast and appear often in real code.
Let us walk through the most common ones.
#include <stdio.h>
int main(void) {
unsigned x = 6;
printf("x & 1 = %u (odd if 1)\n", x & 1);
return 0;
}Even or Odd
The lowest bit tells parity. x & 1 is 1 for odd numbers and 0 for even numbers.
#include <stdio.h>
int main(void) {
for (unsigned x = 0; x < 5; x++) {
printf("%u is %s\n", x, (x & 1) ? "odd" : "even");
}
return 0;
}All lessons in this course
- Bitwise Operators
- Shifts
- Bit Masks and Flags
- Practical Bit Tricks