Skip to content
BetterDL

Wraparound

Also called: modular arithmetic, modulo arithmetic, fixed-width arithmetic

The way fixed-width arithmetic rolls over: a result too big or too small for n bits keeps only its low n bits, so values repeat every 2ⁿ, like a clock.

Real hardware stores numbers in a fixed number of bits. When a result doesn't fit, the extra high bits are simply dropped and the value wraps around, like a clock going from 12 back to 1, or an odometer rolling from 999999 to 000000.

In n bits, arithmetic works modulo 2ⁿ: adding or subtracting 2ⁿ never changes the stored pattern. In 4 bits:

  • 1111 + 1 = 0000 (15 + 1 wraps to 0)
  • 0000 − 1 = 1111 (0 − 1 wraps to 15)

Picture the 16 four-bit patterns arranged in a circle. Adding moves clockwise; subtracting moves counterclockwise.

Wraparound isn't a bug in itself. It's what makes twos complement work: one step back from 0000 lands on 1111, which is why 1111 means −1. And because adding 2ⁿ − x lands in the same place as subtracting x, an adder can subtract.

It becomes a problem when you didn't expect it. Crossing the seam between 1111 and 0000 is unsigned overflow; crossing the seam between 0111 and 1000 is signed overflow. Both happen silently unless you check the status flags.

Worked example

Example

A 6-bit counter at its limits

Two seams on the same wheel of 64 patterns.

1
−32
0
16
0
8
0
4
0
2
0
1
  1. 1.

    111111 + 1 = 1 000000. Keep 6 bits: 000000. Unsigned 63 + 1 wrapped to 0. Signed −1 + 1 = 0, which is correct.

  2. 2.

    011111 + 1 = 100000. Unsigned 31 + 1 = 32, which is correct. Signed +31 + 1 wrapped to −32: signed overflow.

Common mistakes

  • Assuming hardware stops at the largest value. It wraps.

  • Thinking every wrap is an error. Two's complement arithmetic that stays in range relies on it.

  • Forgetting it works downward too: 0 − 1 gives all 1s.

Practice Wraparound

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Wraparound is taught in Number Systems.