</>EmbeddedInterview

How do you compute x % 8 or x / 8 using bit operations?

EasyBit Manipulation

Short answer: For an unsigned x and a power-of-two divisor 2ᵏ, x / 2ᵏ == x >> k and x % 2ᵏ == x & (2ᵏ - 1). So x / 8 == x >> 3 and x % 8 == x & 7.

uint32_t div8(uint32_t x) { return x >> 3; }
uint32_t mod8(uint32_t x) { return x & 7u; }

Why: dividing by 8 drops the last three binary digits (like dividing by 1000 drops three decimal digits), and those three dropped bits are exactly the remainder.

Example: x = 29 = 0b11101 → x >> 3 = 0b11 = 3, x & 7 = 0b101 = 5, and 3 * 8 + 5 = 29.

Signed values are different. C rounds integer division toward zero, so -9 / 8 == -1 and -9 % 8 == -1. But -9 >> 3 == -2 (arithmetic shift rounds toward minus infinity) and -9 & 7 == 7. That is why for int x the compiler emits a few extra instructions to correct the result. If the value is never negative, make it unsigned and you get the single instruction.

You rarely need to write the shift yourself. Any optimising compiler turns x / 8 into a shift for unsigned operands. Write the arithmetic that expresses your intent.

Where the mask form is important: ring buffers.

#define BUF_SIZE 64u                       /* must be a power of two */
head = (head + 1u) & (BUF_SIZE - 1u);      /* wraps 63 -> 0, no division */

On a Cortex-M0/M0+ there is no hardware divide instruction at all, so avoiding % with a non-constant divisor saves a call to a slow library routine.