</>EmbeddedInterview

How do you check if a number is even or odd using bitwise operators?

EasyBit Manipulation

Short answer: Test the lowest bit: (n & 1) == 0 means even and (n & 1) == 1 means odd. Every odd number has bit 0 set, because all other bits contribute even values.

#include <stdbool.h>

bool is_even(unsigned n) { return (n & 1u) == 0; }
bool is_odd(unsigned n)  { return (n & 1u) != 0; }

Why: a binary number is b0·1 + b1·2 + b2·4 + .... Everything except b0 is a multiple of 2, so b0 alone decides odd or even.

Negative numbers: in two's complement (all modern CPUs, and required by C23), -3 is ...11101, so -3 & 1 == 1 and the test still works. Compare with %: -3 % 2 == -1 in C, so n % 2 == 1 is false for negative odd numbers. That is a real bug. Write n % 2 != 0 if you use %.

Speed: compilers turn n % 2 == 0 into a single AND, so there is no performance reason to prefer the bitwise form. Use whichever reads better.

Related one-liners

  • Multiple of 4: (n & 3) == 0.
  • Multiple of 2ᵏ: (n & ((1u << k) - 1)) == 0.
  • Round down to even: n & ~1u.