---
title: Division in hardware
heading: Long division one bit at a time, dividing by constants without dividing, and the trouble with negative numbers
eyebrow: C7 · Lesson 21 · Division in hardware
xp: 40
---

::: hook
Lesson 20 built multipliers that finish in a few gate delays. Division is harder: each quotient bit depends on whether the previous subtraction went negative, so the work is inherently sequential, and a 32-bit divide takes tens of clock cycles even in fast processors. Hardware designers have three answers: do it one bit per cycle with a small circuit, avoid it by multiplying with a precomputed reciprocal when the divisor is a constant, and shift when it's a power of two. The last is where a classic bug lives: shifting a negative number right doesn't round the way division does.
:::

::: play
- Long division in binary, one bit per step. The remainder doubles and takes in the next dividend bit; if it's at least the divisor, the divisor is subtracted and the quotient bit is 1.
- Drag the dividend and divisor and step through. The number of steps is the number of dividend bits, whatever the values.
- The curve is the remainder after each step for the chosen values, which always stays below the divisor.
:::

```sim plot
view: graph
x: k = 0..8
y: R = 0..30
slider: N = 1..255 step 1 = 200
slider: D = 1..40 step 1 = 7
plot: floor(N/2^(8 - floor(k)))  - D*floor(floor(N/2^(8 - floor(k)))/D) | samples: 800 | label: remainder after step k
readout: quotient = floor(N/D)
readout: remainder = N - D*floor(N/D)
```

::: predict
## A C program computes −7 / 2 with integers. A compiler that "optimizes" it into an arithmetic right shift by one bit would get what?

- [ ] −3, the same as division
- [x] −4, because a shift rounds toward minus infinity
- [ ] 3, because the sign is lost
- [ ] 124, because the shift is unsigned

::: reveal
−4. In two's complement, −7 is 1001; shifting right arithmetically gives 1100, which is −4: the shift rounds down, toward minus infinity. C's division truncates toward zero, giving −3 with a remainder of −1. Compilers fix this by adding 1 (in general $2^k - 1$) to negative dividends before shifting by $k$.
:::
:::

::: nameit
## Restoring division

To divide an $n$-bit $N$ by $D$, keep a remainder $R$, starting at 0. For each bit of $N$ from the top:

1. $R \leftarrow 2R + $ (next bit of $N$)
2. If $R \ge D$: $R \leftarrow R - D$ and the quotient bit is 1; otherwise it's 0.

After $n$ steps the quotient bits form $Q = \lfloor N/D\rfloor$ and $R = N - QD$. The hardware is a subtractor, a comparator (the subtractor's borrow out), a shift register and a counter: one quotient bit per cycle. It's called restoring because the simplest form subtracts first and adds $D$ back when the result went negative.

**Non-restoring** division skips the add-back: after a negative result it adds $D$ on the next step instead of subtracting, which saves time per step. Fast processors use **SRT** division, which produces two or more quotient bits per cycle from a small lookup table, and even then a 64-bit divide costs tens of cycles, ten or more times a multiply.

## Dividing by a constant

If $D$ is known in advance, multiply by a scaled reciprocal and shift:

$$\left\lfloor\frac xD\right\rfloor = \left\lfloor\frac{x \cdot M}{2^s}\right\rfloor, \qquad M = \left\lceil\frac{2^s}{D}\right\rceil$$

which is exact for every $n$-bit $x$ when $s$ is large enough: roughly $n + \log_2 D$. For $D$ = 10 and 16-bit $x$, $M$ = 52 429 and $s$ = 19. Compilers do this automatically for division by constants; it turns a 30-cycle divide into a 3-cycle multiply.

## Powers of two and negative numbers

Dividing by $2^k$ is a right shift. For unsigned numbers it's exact. For signed numbers, an arithmetic shift rounds toward −∞, but C, Java and most hardware divide instructions truncate toward zero, with a remainder that takes the dividend's sign: $-7/2 = -3$ remainder $-1$. Adding $2^k - 1$ to a negative dividend before the shift gives the truncated result.
:::

::: example
## Divide 13 (1101) by 3 (0011) with the restoring algorithm.

::: solution
1. **Shift in one bit per step.** Each step doubles the partial remainder R, adds the next bit of 1101, and subtracts 3 when it can:

| Step | $R \leftarrow 2R$ + bit | $R \ge 3$? | $R$ after | Quotient bit |
|---|---|---|---|---|
| 1 | 0 + 1 = 1 | no | 1 | 0 |
| 2 | 2 + 1 = 3 | yes | 0 | 1 |
| 3 | 0 + 0 = 0 | no | 0 | 0 |
| 4 | 0 + 1 = 1 | no | 1 | 0 |

2. **Read the result.** The quotient is 0100 = 4 and the remainder 1:
   $$13 = 4 \times 3 + 1$$
3. **Count the steps.** Four steps for four bits, regardless of the values.

**Answer:** the quotient is 4 (0100) and the remainder 1.
:::
:::

::: example
## Show that $\lfloor x/10\rfloor = \lfloor 52\,429x/2^{19}\rfloor$ for 16-bit $x$, by bounding the error.

::: solution
1. **Write the multiplier as a fraction.**
   $$\frac{52\,429}{2^{19}} = 0.100\,000\,381\,5$$
   so $52\,429x/2^{19} = x/10 + \epsilon x$ with $\epsilon = 3.815 \times 10^{-7}$.
2. **Bound the excess.** For $x < 65\,536$, the excess $\epsilon x$ is under $0.025$.
3. **Compare with the fractions.** The fractional part of $x/10$ is a multiple of 0.1, at most 0.9, so adding less than 0.025 can never push it past the next integer: the floors agree.
4. **Check.** A program that checks all 65 536 values confirms it.
5. **Why it's useful.** On a microcontroller without a divide instruction, that's one 16 × 16 multiply and a shift instead of a slow software loop.

**Answer:** the error $\epsilon x$ stays under 0.025, too small to carry a fraction of at most 0.9 past the next integer, so the two floors agree for every 16-bit $x$.
:::
:::

::: example
## A 32-bit restoring divider in a 500 MHz design takes one cycle per quotient bit plus two cycles of setup. How long is a divide, and how does that compare with a multiplier that finishes in 3 cycles? What would radix-4 SRT do?

::: solution
1. **Divide time.** $32 + 2 = 34$ cycles at 2 ns:
   $$\begin{aligned} t &= 34 \times 2\ \text{ns} \\ &= 68\ \text{ns} \end{aligned}$$
2. **Compare with the multiplier.** Its 3 cycles take 6 ns, so the divide is more than ten times slower.
3. **Radix-4 SRT.** It produces two quotient bits per cycle, so about $16 + 2 = 18$ cycles, 36 ns.
4. **What compilers do.** That's why compilers replace division by constants with multiplication, and why code in tight loops is written to multiply by reciprocals.

**Answer:** 68 ns, more than ten times the multiplier's 6 ns; radix-4 SRT would take about 36 ns.
:::
:::

::: check
given: N = 20..255 int; D = 3..15 int
answer: floor(N/D)

## A restoring divider computes {N} ÷ {D}. What quotient does it produce?

::: right
Right: {answer}, with remainder {N} − {answer} × {D}.
:::

::: misses
- [any] Not yet. The quotient is $\lfloor N/D\rfloor$.
:::
:::

::: check
given: N = 100 | 125 | 200 | 233; D = 7 | 9 | 13
answer: N - D*floor(N/D)
tolerance: 0.5%

## What remainder does the divider leave for {N} ÷ {D}?

::: right
Right: {answer}.
:::

::: misses
- [floor(N/D)] That's the quotient.
- [any] Not yet. $R = N - D\lfloor N/D\rfloor$.
:::
:::

::: check
given: n = 8 | 16 | 32 | 64
answer: n
tolerance: 0.5%

## A restoring divider produces one quotient bit per step. How many steps does an {n}-bit by {n}-bit division take, not counting setup?

::: right
Right: {answer}, one per dividend bit, whatever the values.
:::

::: misses
- [n/2] That's radix-4 SRT, which retires two bits a step.
- [any] Not yet. One step per quotient bit.
:::
:::

::: check
given: x = -7 | -13 | -27 | -45 | -99; p = 2 | 4 | 8
answer: -floor(-x/p)
tolerance: 0.5%

## In C, what is `{x} / {p}` for signed integers?

::: right
Right: {answer}. C truncates toward zero.
:::

::: misses
- [floor(x/p)] That's an arithmetic right shift, which rounds toward minus infinity. C truncates toward zero.
- [any] Not yet. Divide and drop the fraction, toward zero.
:::
:::

::: check
kind: choice

## A compiler replaces `y = x / 8` with `y = x >> 3` for a signed `int x`. When does the result differ from C's division?

- [x] When x is negative and not a multiple of 8
- [ ] When x is positive and not a multiple of 8
- [ ] Never; shifting by 3 divides by 8
- [ ] When x exceeds 2³¹ / 8

::: right
Right. The arithmetic shift rounds toward minus infinity and C truncates toward zero; they agree for non-negative x and for exact multiples. Compilers add 7 to negative x before shifting.
:::

::: misses
- [2] For non-negative x, both round down.
- [3] They differ for negative x that isn't a multiple of 8.
- [4] There's no overflow issue; the problem is rounding direction.
:::
:::

::: check
kind: python
given: n = 8 | 12 | 16; D = 3 | 7 | 10 | 13

## Write `divide(N, Dv)` returning `(q, r)` by the restoring algorithm for `n`-bit unsigned `N` ({n} bits), counting the steps in a global list `steps` (append 1 per quotient bit). Then find the smallest shift `s` (search from `n` upward) such that `M = ceil(2**s / D)` gives `(x*M) >> s == x // D` for every `n`-bit `x`, with `D` = {D}, and set `s_min` and `M_min`.

```python starter
steps = []
def divide(N, Dv):
    return N // Dv, N % Dv
s_min = n
M_min = -(-(1 << n) // D)
```

```python solution
steps = []
def divide(N, Dv):
    R = Q = 0
    for i in range(n - 1, -1, -1):
        steps.append(1)
        R = 2 * R + ((N >> i) & 1)
        if R >= Dv:
            R -= Dv
            Q |= 1 << i
    return Q, R
s = n
while True:
    M = -(-(1 << s) // D)
    if all((x * M) >> s == x // D for x in range(1 << n)):
        break
    s += 1
s_min, M_min = s, M
```

```python tests
import random
rng = random.Random(3)
for _ in range(500):
    N, Dv = rng.randrange(1 << n), rng.randrange(1, 1 << n)
    steps.clear()
    assert divide(N, Dv) == (N // Dv, N % Dv), f"divide({N}, {Dv}) should give {(N // Dv, N % Dv)}."
    assert len(steps) == n, "The restoring algorithm takes exactly n steps."
s = n
while True:
    M = -(-(1 << s) // D)
    if all((x * M) >> s == x // D for x in range(1 << n)): break
    s += 1
assert (s_min, M_min) == (s, M), f"The smallest shift is {s} with M = {M}."
```

::: right
Right. The search finds the shift a compiler would pick; for $D$ = 10 on 16 bits it lands on 19 with $M$ = 52 429.
:::
:::

::: explain
## Why is division so much slower than multiplication in hardware, even though both are built from adders?

::: model
A multiplier forms all its partial products at once, since each is just the multiplicand ANDed with one multiplier bit, and then adds them in a tree of adders whose depth grows only with the logarithm of the number of bits. Division can't do that: whether the next quotient bit is 1 depends on the sign of the remainder after the previous subtraction, so each step must wait for the previous one to finish, all the way down a carry chain. The work is a chain of n dependent subtractions instead of a tree, so it takes about n steps, or n/2 for radix-4 SRT, against a few for multiplication. That's why compilers turn division by constants into multiplication by reciprocals.
:::
:::

::: practice

::: check
given: N = 50..250 int; D = 3..9 int
answer: floor(N/D)

## What quotient does {N} ÷ {D} give in hardware?

::: misses
- [any] $\lfloor N/D\rfloor$.
:::
:::

::: check
given: k = 1 | 2 | 3 | 4
answer: 2^k - 1

## Before arithmetic-shifting a negative number right by {k} bits to divide by $2^{\given{k}}$ with C's rounding, what should be added to it?

::: misses
- [2^k] Add one less than the divisor.
- [any] $2^k - 1$.
:::
:::
:::
