---
title: Arithmetic lab
heading: Lookahead carries, Booth multiplication, division, BCD and saturation, in Python
eyebrow: C7 · Lesson 53 · Arithmetic lab
xp: 50
---

::: hook
Lessons 16 to 20 built adders, multipliers and number formats as circuits. Each algorithm a circuit implements can be written first as a few lines of code that work bit by bit, exactly as the hardware does, and checked against ordinary arithmetic on every input. In this lab you'll compute carries by lookahead, multiply signed numbers with Booth's algorithm, divide by restoring subtraction, add decimal digits in BCD, and add with saturation, testing each exhaustively over small widths, which is how hardware arithmetic is verified.

::: play
- The curve shows how many add or subtract operations Booth's algorithm needs, on average, against the number of bits, compared with plain shift-and-add, which adds once per 1 bit in the multiplier.
- Booth adds only at the boundaries of runs of 1s. For random multipliers that's about half the bits either way; for multipliers with long runs of 1s, far fewer.
- The readout gives the worst case for each: Booth's is a multiplier of alternating 1s and 0s.
:::
:::

```sim plot
view: graph
x: n = 4..64
y: k = 0..70
plot: n/2 | label: shift-and-add, random multiplier | samples: 50
plot: n/2 | color: ch2 | label: Booth, random multiplier | samples: 50
plot: n | color: ch3 | label: worst case for either | samples: 50
readout: Booth for a run of 1s of any length = 2 | digits: 1
```

::: predict
## Booth's algorithm multiplies by 0111 1110 (126). How many additions or subtractions does it do, against shift-and-add's one per 1 bit?

- [ ] 6, the same
- [x] 2: one subtraction where the run of 1s starts and one addition where it ends
- [ ] 8
- [ ] 1

::: reveal
Two. Booth rewrites a run of 1s from bit i to bit j as $2^{j+1} - 2^i$: here $128 - 2$ = 126, one subtraction of the multiplicand shifted by 1 and one addition shifted by 7. Shift-and-add would add six times. Booth handles signed numbers without special cases, which is its main use in hardware.
:::
:::

::: nameit
## Lookahead carries

With $g_i = a_ib_i$ and $p_i = a_i \oplus b_i$, every carry can be written directly from the inputs:

$$c_{i+1} = g_i + p_ig_{i-1} + p_ip_{i-1}g_{i-2} + \cdots + p_ip_{i-1}\cdots p_0c_0.$$

Computing each carry this way, with no carry waiting on another, is what a lookahead adder does in parallel.

## Booth multiplication

Scan the multiplier's bits from the bottom, each with the bit below it (a 0 below the lowest). At a pair 10 (a run of 1s starts), subtract the multiplicand; at 01 (a run ends), add it; otherwise do nothing. Shift the accumulator and multiplier right together, arithmetically, after each bit. After n steps the 2n-bit result is the signed product.

## Restoring division

For each dividend bit from the top: shift it into a partial remainder; if the remainder is at least the divisor, subtract and set that quotient bit to 1. After n steps, the quotient and remainder are complete.

## BCD addition and saturation

Add BCD digit by digit; any digit sum above 9 gets 6 added and carries into the next digit. A **saturating** n-bit adder clamps results to $-2^{n-1}$ and $2^{n-1} - 1$ instead of wrapping.
:::

::: example
## Multiply −7 by 3 with 4-bit Booth's algorithm.

::: solution
1. **Write the multiplier.** The multiplier 3 is 0011.
2. **Bit 0.** With a 0 below it's 10: subtract −7, so the accumulator gains 7, then shift.
3. **Bit 1.** With 1 below it's 11: nothing.
4. **Bit 2.** With 1 below it's 01: add −7.
5. **Bit 3.** With 0 below: nothing.
6. **Read the result.** Two operations, and the 8-bit result reads −21.
7. **Why it works.** Booth treated 0011 as $4 - 1$:
   $$-7 \times 4 - (-7) \times 1 = -21$$

**Answer:** −21, from two operations.
:::
:::

::: example
## Divide 143 by 11 by restoring division with 8 bits.

::: solution
1. **Shift in until it fits.** Shifting in 143 = 1000 1111 bit by bit, the partial remainder first reaches 11 or more at the fifth bit: 1000 1 = 17, subtract 11 → 6.
2. **Shift in the rest.** 6 → 13 (subtract → 2), 2 → 5, 5 → 11 (subtract → 0).
3. **Read the result.** The quotient bits form 0000 1101 = 13 and the remainder is 0:
   $$143 = 13 \times 11$$
4. **The cost.** Each step is a shift and a compare-subtract, so an n-bit divider takes n steps, far more than an adder.

**Answer:** the quotient is 13 and the remainder 0.
:::
:::

::: example
## Add the BCD numbers 59 and 27, and 999 and 1.

::: solution
1. **Units.** 9 + 7 = 16, above 9, so add 6:
   $$\begin{aligned} 16 + 6 &= 22 \\ &= 1\,0110_2 \end{aligned}$$
   digit 6, carry 1.
2. **Tens.**
   $$5 + 2 + 1 = 8$$
   so the result is 86.
3. **999 + 1.** Each digit overflows in turn: 10 → 0 carry 1, three times, giving 1000.
4. **In hardware.** The correction ripples like a carry, and BCD hardware is a binary adder with a correction stage per digit.

**Answer:** 59 + 27 = 86, and 999 + 1 = 1000.
:::
:::

::: check
kind: python

## Step 1. Write `cla_carries(a, b, cin, n)` returning the list of carries $c_0$ (= cin) to $c_n$, each computed directly from the g and p terms by the lookahead formula, not from the carry before it.

```python starter
def cla_carries(a, b, cin, n):
    c = [cin]
    for i in range(n):
        c.append(((a >> i) & (b >> i)) & 1)
    return c

print(cla_carries(0b1011, 0b0110, 0, 4))
```

```python solution
def cla_carries(a, b, cin, n):
    g = [((a >> i) & (b >> i)) & 1 for i in range(n)]
    p = [((a >> i) ^ (b >> i)) & 1 for i in range(n)]
    c = [cin]
    for i in range(n):
        term, prod = g[i], p[i]
        for j in range(i - 1, -1, -1):
            term |= prod & g[j]
            prod &= p[j]
        term |= prod & cin
        c.append(term)
    return c

print(cla_carries(0b1011, 0b0110, 0, 4))
```

```python tests
assert cla_carries(0b1011, 0b0110, 0, 4) == [0, 0, 1, 1, 1], "1011 + 0110 carries out of bits 1, 2 and 3."
for a in range(16):
    for b in range(16):
        for c in (0, 1):
            cs = cla_carries(a, b, c, 4)
            assert cs[4] == (a + b + c) >> 4, f"Carry out wrong for {a} + {b} + {c}"
            assert all(cs[i] == ((a % (1 << i)) + (b % (1 << i)) + c) >> i for i in range(5)), "Every carry must match."
```

::: right
Right. Each carry is a sum of products of the inputs: wide gates, but no chain.
:::
:::

::: check
kind: python

## Step 2. Write `booth(a, b, n)` returning `(product, ops)`: the signed product of the n-bit two's-complement numbers a and b by radix-2 Booth, and the number of additions plus subtractions it performed.

```python starter
def booth(a, b, n):
    return a * b, n

print(booth(-7, 3, 4))
```

```python solution
def booth(a, b, n):
    mask = (1 << n) - 1
    A, Q, q_1 = 0, b & mask, 0
    ops = 0
    for _ in range(n):
        pair = (Q & 1, q_1)
        if pair == (1, 0):
            A -= a; ops += 1
        elif pair == (0, 1):
            A += a; ops += 1
        q_1 = Q & 1
        Q = (Q >> 1) | ((A & 1) << (n - 1))
        A >>= 1
    return A * (1 << n) + Q, ops

print(booth(-7, 3, 4))
```

```python tests
assert booth(-7, 3, 4) == (-21, 2), "−7 × 3 = −21 in two operations."
assert booth(13, 11, 6) == (143, 4) and booth(-8, -8, 4) == (64, 1), "Including the most negative value."
assert all(booth(a, b, 5)[0] == a * b for a in range(-16, 16) for b in range(-16, 16)), "Every 5-bit pair."
assert booth(5, 126, 8)[1] == 2, "A single run of 1s costs two operations."
```

::: right
Right. Keeping the accumulator one bit wider than the operands is what lets the most negative multiplicand work.
:::
:::

::: check
kind: python

## Step 3. Write `restoring_divide(N, D, n)` returning `(quotient, remainder)` for unsigned n-bit N and D > 0.

```python starter
def restoring_divide(N, D, n):
    return N // D, 0

print(restoring_divide(143, 11, 8))
```

```python solution
def restoring_divide(N, D, n):
    R, Q = 0, 0
    for i in range(n - 1, -1, -1):
        R = (R << 1) | ((N >> i) & 1)
        if R >= D:
            R -= D
            Q |= 1 << i
    return Q, R

print(restoring_divide(143, 11, 8))
```

```python tests
assert restoring_divide(143, 11, 8) == (13, 0) and restoring_divide(100, 7, 8) == (14, 2), "143/11 and 100/7."
assert all(restoring_divide(N, D, 6) == divmod(N, D) for N in range(64) for D in range(1, 64)), "Every 6-bit pair."
```

::: right
Right. Long division in base 2: each quotient bit is a single compare.
:::
:::

::: check
kind: python

## Step 4. Write `bcd_add(x, y)` adding two BCD numbers (each a Python integer whose hex digits are the decimal digits, like 0x59 for 59) and returning the BCD sum.

```python starter
def bcd_add(x, y):
    return x + y

print(hex(bcd_add(0x59, 0x27)))
```

```python solution
def bcd_add(x, y):
    res, carry, shift = 0, 0, 0
    while x or y or carry:
        s = (x & 0xF) + (y & 0xF) + carry
        carry = 0
        if s > 9:
            s += 6
            carry = 1
        res |= (s & 0xF) << shift
        x >>= 4; y >>= 4; shift += 4
    return res

print(hex(bcd_add(0x59, 0x27)))
```

```python tests
assert bcd_add(0x59, 0x27) == 0x86 and bcd_add(0x999, 0x1) == 0x1000, "59 + 27 and 999 + 1."
for a in range(1000):
    for b in (0, 1, 9, 47, 999):
        assert bcd_add(int(str(a), 16), int(str(b), 16)) == int(str(a + b), 16), f"{a} + {b}"
```

::: right
Right. Adding 6 to an overflowing digit skips the six codes BCD never uses.
:::
:::

::: check
kind: python

## Step 5. Write `saturating_add(a, b, n)` returning the n-bit signed saturating sum of a and b.

```python starter
def saturating_add(a, b, n):
    s = (a + b) & ((1 << n) - 1)
    return s - (1 << n) if s >> (n - 1) else s

print(saturating_add(100, 50, 8))
```

```python solution
def saturating_add(a, b, n):
    s = a + b
    return max(-(1 << (n - 1)), min((1 << (n - 1)) - 1, s))

print(saturating_add(100, 50, 8))
```

```python tests
assert saturating_add(100, 50, 8) == 127 and saturating_add(-100, -50, 8) == -128, "Clamped at both ends."
assert saturating_add(20, 30, 8) == 50 and saturating_add(-128, 127, 8) == -1, "No clamping needed."
```

::: right
Right. An overflow becomes a small error of the right sign instead of a wraparound.
:::
:::

::: check
given: b = 2 | 3 | 5; r = 6 | 10 | 20
answer: 2
tolerance: 0

## A multiplier's only 1s are a single run of {r} consecutive bits starting at bit {b}. How many additions or subtractions does Booth's algorithm perform?

::: right
Right: two. One subtraction where the run starts and one addition where it ends, whatever its length.
:::

::: misses
- [r] That's shift-and-add's count, one per 1 bit.
- [any] Booth acts only at the boundaries of runs.
:::
:::

::: explain
## Why are hardware arithmetic algorithms usually verified by exhaustive testing at small widths?

::: model
An arithmetic algorithm implemented bit by bit has many corner cases: carries that ripple through every bit, the most negative two's-complement number, remainders exactly equal to the divisor, digits that overflow in BCD. A few hand-picked tests easily miss one. At a small width the number of input combinations is small enough to try them all and compare each with ordinary arithmetic, so every corner case is covered. Because the same algorithm scales by repeating the same bit-level steps, an algorithm correct for every 5-bit or 6-bit input is very likely correct at 32 or 64 bits, where exhaustive testing would be impossible.
:::
:::

::: practice

::: check
given: N = 100 | 200 | 250; D = 7 | 9 | 13
answer: floor(N/D)
tolerance: 0

## Restoring division: quotient of {N} by {D}?

::: misses
- [any] The whole number of times D fits.
:::
:::
:::
