---
title: "From Gates to an Arithmetic Unit"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 12
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/12-from-gates-to-an-arithmetic-unit
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 12 — From Gates to an Arithmetic Unit

Book 1 ended its tour of logic gates with a half adder: two bits in, their sum and their carry out. A processor adds two numbers of $64$ bits each, billions of times a second, and it has no other material than such gates. This chapter builds the missing steps one at a time: an adder for three bits, an adder for whole numbers, a circuit that chooses, an [arithmetic and logic unit](#def-g11-gates-to-arithmetic-unit-alu) with its [flags](#def-g11-gates-to-arithmetic-unit-flag), and finally a circuit that remembers. Each one is simulated in Python, gate by gate, and checked on every input.

**You already know.**

A gate computes one bit from one or two bits: NOT, AND, OR, XOR, and NOR, which is NOT OR. A half adder computes $a + b$ for two bits: the sum bit is $a \oplus b$ and the carry is $a \wedge b$. De Morgan’s laws turn an AND into an OR of negations and back. A transistor works as a switch, which is how gates are built (Book 1, grade 9). On $n$ bits, [two’s complement](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-twos-complement) writes $-x$ as $2^n - x$ (the chapter on numbers in binary).

The gates of the chapter are Python functions on the bits $0$ and $1$, in the module `gates.py`: `NOT(a)` returns $1 - a$, `AND`, `OR` and `XOR` use Python’s bitwise operators, and `NOR(a, b)` is `NOT(OR(a, b))`. Every circuit below is written with these five functions only.

![A relay: an electromagnet that pulls metal contacts open or shut, a switch worked by a current. Machines such as the Harvard Mark II built their logic from relays before transistors replaced them (Book 1, grade 7). Photograph: Duncan Smith, public domain.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-gates-to-arithmetic-unit/img-48f51a19de7e.jpg)

*A relay: an electromagnet that pulls metal contacts open or shut, a switch worked by a current. Machines such as the Harvard Mark II built their logic from relays before transistors replaced them (Book 1, grade 7). Photograph: Duncan Smith, public domain.*

## 12.1 The full adder

To add two numbers written in binary, each column adds three bits: the two digits of the column, and the carry from the column on its right. The half adder takes only two.

**Definition 12.1 (Full adder).**

A *full adder* is a circuit with three input bits $a$, $b$, $c$ and two output bits $s$ and $c'$ such that $a + b + c = 2c' + s$: $s$ is the sum bit, and $c'$ the carry out.

A [full adder](#def-g11-gates-to-arithmetic-unit-full-adder) is made of two half adders and an OR gate. The first half adder adds $a$ and $b$, the second adds the carry $c$ to their sum bit, and since the two carries cannot both be $1$, an OR combines them.

![A full adder: two half adders and an OR gate, five gates in all. A dot marks where a wire branches; wires that cross without a dot are not connected.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-gates-to-arithmetic-unit/fig-e2395f7b2912.svg)

*A [full adder](#def-g11-gates-to-arithmetic-unit-full-adder): two half adders and an OR gate, five gates in all. A dot marks where a wire branches; wires that cross without a dot are not connected.*

```python
from gates import AND, OR, XOR


def half_adder(a, b):
    """Two bits in; their sum bit and their carry out."""
    return XOR(a, b), AND(a, b)


def full_adder(a, b, c):
    """Three bits in (c is the carry from the column before); sum and carry out."""
    s1, c1 = half_adder(a, b)
    s, c2 = half_adder(s1, c)
    return s, OR(c1, c2)


if __name__ == "__main__":
    print("a b c | s carry | a+b+c")
    for a in (0, 1):
        for b in (0, 1):
            for c in (0, 1):
                s, carry = full_adder(a, b, c)
                assert 2 * carry + s == a + b + c   # checked on all 8 rows
                print(f"{a} {b} {c} | {s}   {carry}   |   {a + b + c}")
```

***Listing 12.1.** The [full adder](#def-g11-gates-to-arithmetic-unit-full-adder), checked on its eight rows. code/grade-11/01-gates-to-arithmetic-unit/listings/full_adder.py*

```
$ python full_adder.py
a b c | s carry | a+b+c
0 0 0 | 0   0   |   0
0 0 1 | 1   0   |   1
0 1 0 | 1   0   |   1
0 1 1 | 0   1   |   2
1 0 0 | 1   0   |   1
1 0 1 | 0   1   |   2
1 1 0 | 0   1   |   2
1 1 1 | 1   1   |   3
```

***Output 12.1.** The truth table: the two outputs, read as a binary number $c's$, are $a + b + c$.*

Eight rows are all the inputs there are, so the `assert` of line 22 proves the circuit correct: an *exhaustive* check. A circuit whose outputs depend only on its present inputs, as here, is called combinational.

**Definition 12.2 (Combinational and sequential circuits).**

A *combinational circuit* computes its outputs from its present inputs only: the same inputs always give the same outputs. A *sequential circuit* also depends on what happened before, because some of its outputs are fed back to its inputs: it has a memory.

## 12.2 Chaining adders

**Definition 12.3 (Ripple-carry adder).**

A *ripple-carry adder* on $n$ bits is a row of $n$ [full adders](#def-g11-gates-to-arithmetic-unit-full-adder), one per column: the adder of column $i$ adds $a_i$, $b_i$ and the carry $c_i$ from column $i - 1$, and passes its carry out $c_{i+1}$ to column $i + 1$. The first carry $c_0$ is an input, usually $0$; the last, $c_n$, is the carry out of the sum.

![A 4-bit ripple-carry adder, drawn with the least significant column on the right, as numbers are written. The carry chain, in red, crosses every full adder: column 3 cannot finish before column 0 has.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-gates-to-arithmetic-unit/fig-20b23d874d51.svg)

*A $4$-bit [ripple-carry adder](#def-g11-gates-to-arithmetic-unit-ripple), drawn with the least significant column on the right, as numbers are written. The carry chain, in red, crosses every [full adder](#def-g11-gates-to-arithmetic-unit-full-adder): column $3$ cannot finish before column $0$ has.*

The simulation keeps the bits of a number in a list, least significant first, so that index $i$ is the column of weight $2^i$.

```python
from full_adder import full_adder


def to_bits(x, n):
    """The n bits of x, least significant first."""
    return [(x >> i) & 1 for i in range(n)]


def from_bits(bits):
    return sum(bit << i for i, bit in enumerate(bits))


def add_bits(a, b, carry=0):
    """Ripple-carry addition: one full adder per column, the carry passed along."""
    out = []
    carries = [carry]
    for x, y in zip(a, b):
        s, carry = full_adder(x, y, carry)
        out.append(s)
        carries.append(carry)
    return out, carries


if __name__ == "__main__":
    for x, y in [(100, 27), (200, 100), (100, 100)]:
        bits, carries = add_bits(to_bits(x, 8), to_bits(y, 8))
        result = from_bits(bits)
        overflow = carries[7] != carries[8]   # carry into bit 7 differs from carry out
        print(f"{x:3} + {y:3} = {result:3}  carry out {carries[8]}"
              f"  signed overflow {int(overflow)}  carries {carries[::-1]}")
```

***Listing 12.2.** An $8$-bit adder from eight [full adders](#def-g11-gates-to-arithmetic-unit-full-adder). code/grade-11/01-gates-to-arithmetic-unit/listings/ripple.py*

```
$ python ripple.py
100 +  27 = 127  carry out 0  signed overflow 0  carries [0, 0, 0, 0, 0, 0, 0, 0, 0]
200 + 100 =  44  carry out 1  signed overflow 0  carries [1, 1, 0, 0, 0, 0, 0, 0, 0]
100 + 100 = 200  carry out 0  signed overflow 1  carries [0, 1, 1, 0, 0, 1, 0, 0, 0]
```

***Output 12.2.** The carries are printed from $c_8$ down to $c_0$, in the order of the bits.*

The second sum, $200 + 100 = 300$, does not fit in $8$ bits: the result is $300 - 256 = 44$ and the carry out is $1$, which signals the overflow for numbers read without sign. The third sum fits without sign, $200$, but read in [two’s complement](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-twos-complement), $100 + 100$ gives $-56$, a sign change no correct sum of two positive numbers can have. A signed overflow happens exactly when the carry into the last column differs from the carry out of it, which is what line 28 computes.

The same adder subtracts. Flipping every bit of $b$ gives $2^n - 1 - b$; adding $1$ gives $2^n - b$, the [two’s complement](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-twos-complement) of $b$. So $a - b$ is $a + \overline{b} + 1$, modulo $2^n$, and the $+1$ costs nothing: it enters as the first carry $c_0$.

```python
from gates import NOT
from ripple import add_bits, from_bits, to_bits


def sub_bits(a, b):
    """a - b with the same adder: a + (b with every bit flipped) + 1."""
    return add_bits(a, [NOT(bit) for bit in b], carry=1)


for x, y in [(100, 27), (27, 100), (5, 5)]:
    bits, carries = sub_bits(to_bits(x, 8), to_bits(y, 8))
    r = from_bits(bits)
    signed = r - 256 if bits[7] else r
    print(f"{x:3} - {y:3} -> {r:3} (as a signed byte {signed:4})"
          f"  carry out {carries[8]}")
```

***Listing 12.3.** Subtraction through the adder: flip, and carry in $1$. code/grade-11/01-gates-to-arithmetic-unit/listings/subtract.py*

```
$ python subtract.py
100 -  27 ->  73 (as a signed byte   73)  carry out 1
 27 - 100 -> 183 (as a signed byte  -73)  carry out 0
  5 -   5 ->   0 (as a signed byte    0)  carry out 1
```

***Output 12.3.** The carry out of a subtraction is $1$ exactly when $a \ge b$: when it is $0$, the subtraction needed a borrow.*

## 12.3 Choosing and decoding

A processor computes several things at once and keeps one; it also has to turn a number, such as the number of a register, into one wire among several. Two small circuits do these jobs.

**Definition 12.4 (Multiplexer, decoder).**

A *multiplexer* with $k$ select bits has $2^k$ data inputs and one output, equal to the data input whose number is written by the select bits. A *decoder* with $k$ input bits has $2^k$ outputs, of which exactly one is $1$: the one whose number is written by the inputs.

The $2{:}1$ [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) is $(\neg s \wedge x_0) \vee (s \wedge x_1)$: when $s = 0$ the first AND lets $x_0$ through and the second gives $0$, and the reverse when $s = 1$. Three of them make a $4{:}1$ [multiplexer](#def-g11-gates-to-arithmetic-unit-mux).

![A 4:1 multiplexer from three 2:1 multiplexers. The bit s_0 chooses within each pair, then s_1 chooses between the pairs: the output is x_2s_1 + s_0.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-gates-to-arithmetic-unit/fig-2ff5c1c7cce1.svg)

*A $4{:}1$ [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) from three $2{:}1$ [multiplexers](#def-g11-gates-to-arithmetic-unit-mux). The bit $s_0$ chooses within each pair, then $s_1$ chooses between the pairs: the output is $x_{2s_1 + s_0}$.*

```python
from gates import AND, NOT, OR


def mux2(s, x0, x1):
    """x0 if s is 0, x1 if s is 1."""
    return OR(AND(NOT(s), x0), AND(s, x1))


def mux4(s1, s0, x):
    """One of the four inputs x[0..3], chosen by the two bits s1 s0."""
    return mux2(s1, mux2(s0, x[0], x[1]), mux2(s0, x[2], x[3]))


def decoder2(s1, s0):
    """Four outputs; exactly the one numbered s1 s0 is 1."""
    n1, n0 = NOT(s1), NOT(s0)
    return [AND(n1, n0), AND(n1, s0), AND(s1, n0), AND(s1, s0)]


if __name__ == "__main__":
    x = [0, 1, 1, 0]
    print("inputs x0..x3 =", x)
    for s1 in (0, 1):
        for s0 in (0, 1):
            print(f"select {s1}{s0}: mux4 -> {mux4(s1, s0, x)}"
                  f"   decoder -> {decoder2(s1, s0)}")
```

***Listing 12.4.** [Multiplexers](#def-g11-gates-to-arithmetic-unit-mux) and a $2$-to-$4$ [decoder](#def-g11-gates-to-arithmetic-unit-mux). code/grade-11/01-gates-to-arithmetic-unit/listings/mux.py*

```
$ python mux.py
inputs x0..x3 = [0, 1, 1, 0]
select 00: mux4 -> 0   decoder -> [1, 0, 0, 0]
select 01: mux4 -> 1   decoder -> [0, 1, 0, 0]
select 10: mux4 -> 1   decoder -> [0, 0, 1, 0]
select 11: mux4 -> 0   decoder -> [0, 0, 0, 1]
```

***Output 12.4.** The [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) copies the chosen input; the [decoder](#def-g11-gates-to-arithmetic-unit-mux) lights the chosen output.*

## 12.4 An arithmetic and logic unit

**Definition 12.5 (Arithmetic and logic unit).**

An *arithmetic and logic unit* (ALU) is a [combinational circuit](#def-g11-gates-to-arithmetic-unit-combinational) with two numbers $A$ and $B$ as inputs and an operation code; it outputs the result of the chosen operation, and some [flags](#def-g11-gates-to-arithmetic-unit-flag) about that result.

**Definition 12.6 (Flag).**

A *flag* is a bit that an operation sets to describe its result, for the instructions that follow to test. The toy machine of Book 1 has three: $Z$ is $1$ when the result is $0$; $N$ is the last bit of the result, $1$ when it is negative in [two’s complement](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-twos-complement); $C$ is the carry out of an addition, and for a subtraction, $1$ when it needed a borrow; logic operations set $C$ to $0$.

![The usual drawing of an ALU: two numbers enter at the top, the result leaves at the bottom, the operation code comes from the side, and the flags leave on the other side.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-gates-to-arithmetic-unit/fig-db7d20af4f62.svg)

*The usual drawing of an ALU: two numbers enter at the top, the result leaves at the bottom, the operation code comes from the side, and the [flags](#def-g11-gates-to-arithmetic-unit-flag) leave on the other side.*

The ALU below has four operations, coded on two bits: AND $00$, OR $01$, ADD $10$, SUB $11$. Each column computes the AND, the OR and the sum of its bits; a $4{:}1$ [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) per column keeps the one the code asks for. For SUB, both code bits are $1$: an AND of them flips $b$ through an XOR, and the low code bit is the first carry, which adds the $1$ of the subtraction.

```python
from full_adder import full_adder
from gates import AND, NOT, OR, XOR
from mux import mux4
from ripple import from_bits, to_bits

OPS = {"AND": (0, 0), "OR": (0, 1), "ADD": (1, 0), "SUB": (1, 1)}


def alu(op, a, b):
    """8-bit ALU: every column computes all four results, a multiplexer keeps one."""
    s1, s0 = OPS[op]
    carry = s0  # SUB adds 1 through the first carry
    out = []
    for x, y in zip(a, b):
        y2 = XOR(y, AND(s1, s0))  # flip b only for SUB
        s, carry = full_adder(x, y2, carry)
        out.append(mux4(s1, s0, [AND(x, y), OR(x, y), s, s]))
    zero = NOT(OR(OR(OR(out[0], out[1]), OR(out[2], out[3])),
                  OR(OR(out[4], out[5]), OR(out[6], out[7]))))
    c = AND(s1, XOR(carry, s0))  # ADD: the carry; SUB: no carry means a borrow
    return out, {"Z": zero, "N": out[7], "C": c}


if __name__ == "__main__":
    for op, x, y in [("AND", 12, 10), ("OR", 12, 10), ("ADD", 250, 10),
                     ("SUB", 5, 10), ("SUB", 10, 10)]:
        bits, flags = alu(op, to_bits(x, 8), to_bits(y, 8))
        print(f"{op:3} {x:3} {y:3} -> {from_bits(bits):3}  {flags}")
```

***Listing 12.5.** An $8$-bit ALU with four operations and three [flags](#def-g11-gates-to-arithmetic-unit-flag). code/grade-11/01-gates-to-arithmetic-unit/listings/alu.py*

```
$ python alu.py
AND  12  10 ->   8  {'Z': 0, 'N': 0, 'C': 0}
OR   12  10 ->  14  {'Z': 0, 'N': 0, 'C': 0}
ADD 250  10 ->   4  {'Z': 0, 'N': 0, 'C': 1}
SUB   5  10 -> 251  {'Z': 0, 'N': 1, 'C': 1}
SUB  10  10 ->   0  {'Z': 1, 'N': 0, 'C': 0}
```

***Output 12.5.** $5 - 10$ gives $251$, which is $-5$ in [two’s complement](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#def-g10-machine-integers-twos-complement): $N = 1$, and $C = 1$ for the borrow.*

The [flag](#def-g11-gates-to-arithmetic-unit-flag) $Z$ is a NOR of all eight result bits, built as a tree of ORs and one NOT. The [flag](#def-g11-gates-to-arithmetic-unit-flag) $C$ inverts the carry out for a subtraction, so that it means “borrow” as on the toy machine, and is forced to $0$ by the AND with the high code bit for the logic operations. The chapter’s tests run every operation of this ALU on $305$ pairs of numbers and compare the result and the three [flags](#def-g11-gates-to-arithmetic-unit-flag) with the toy machine’s own instructions: they agree on all of them.

**In practice — Faster carries.**

A [ripple-carry adder](#def-g11-gates-to-arithmetic-unit-ripple) is small but slow, since the carry crosses every column. Real processors use adders that compute the carries of a group of columns at once, from the signals $g = a \wedge b$ (the column generates a carry) and $p = a \oplus b$ (it propagates one), at the price of more gates. The weekend problem measures one such idea.

## 12.5 A circuit that remembers

Everything so far forgets its inputs as soon as they change. A register must keep a number after the wires that brought it have moved on. The trick is to feed outputs back to inputs.

![An SR latch: two NOR gates, each fed by the other’s output. S sets Q to 1, R resets it to 0, and with both at 0 the latch keeps the value it had.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-gates-to-arithmetic-unit/fig-4295c9895d3e.svg)

*An SR [latch](#def-g11-gates-to-arithmetic-unit-latch): two NOR gates, each fed by the other’s output. $S$ sets $Q$ to $1$, $R$ resets it to $0$, and with both at $0$ the [latch](#def-g11-gates-to-arithmetic-unit-latch) keeps the value it had.*

**Definition 12.7 (Latch, flip-flop).**

A *latch* is a [sequential circuit](#def-g11-gates-to-arithmetic-unit-combinational) that keeps one bit: the *SR latch* is set to $1$ by its input $S$, reset to $0$ by its input $R$, and keeps its bit while both are $0$. A *flip-flop* keeps one bit too, but changes it only at a precise moment: the *D flip-flop* copies its input $D$ to its output $Q$ at each rising edge of a clock signal, when the clock goes from $0$ to $1$, and ignores $D$ the rest of the time.

The simulation updates both gates at once from their previous outputs, again and again, until nothing changes.

```python
from gates import NOR


def settle(s, r, q, qbar, steps=4):
    """Update both NOR gates at once, again and again, until nothing changes."""
    seen = [(q, qbar)]
    for _ in range(steps):
        q, qbar = NOR(r, qbar), NOR(s, q)
        if (q, qbar) == seen[-1]:
            return seen, True  # stable: the latch holds this state
        seen.append((q, qbar))
    return seen, False


q, qbar = 0, 1
for s, r, what in [(1, 0, "set"), (0, 0, "hold"), (0, 1, "reset"), (0, 0, "hold"),
                   (1, 1, "both"), (0, 0, "release")]:
    seen, stable = settle(s, r, q, qbar)
    q, qbar = seen[-1]
    end = f"Q={q}" if stable else "never settles"
    print(f"S={s} R={r} {what:8} {seen}  ->  {end}")
```

***Listing 12.6.** The SR [latch](#def-g11-gates-to-arithmetic-unit-latch), run until it settles. code/grade-11/01-gates-to-arithmetic-unit/listings/latch.py*

```
$ python latch.py
S=1 R=0 set      [(0, 1), (0, 0), (1, 0)]  ->  Q=1
S=0 R=0 hold     [(1, 0)]  ->  Q=1
S=0 R=1 reset    [(1, 0), (0, 0), (0, 1)]  ->  Q=0
S=0 R=0 hold     [(0, 1)]  ->  Q=0
S=1 R=1 both     [(0, 1), (0, 0)]  ->  Q=0
S=0 R=0 release  [(0, 0), (1, 1), (0, 0), (1, 1), (0, 0)]  ->  never settles
```

***Output 12.6.** The [latch](#def-g11-gates-to-arithmetic-unit-latch) remembers through each *hold*. After $S = R = 1$, releasing both at once leaves it oscillating.*

With $S = R = 1$ both outputs are $0$, so $\overline{Q}$ is no longer the opposite of $Q$; if both inputs then drop at once, both gates see two zeros and switch to $1$, then both see a $1$ and switch back, and so on. A real circuit does not oscillate for ever: one gate is always slightly faster, and the [latch](#def-g11-gates-to-arithmetic-unit-latch) ends in a state that cannot be predicted. This is why $S = R = 1$ is forbidden.

A D [flip-flop](#def-g11-gates-to-arithmetic-unit-latch) is built from [latches](#def-g11-gates-to-arithmetic-unit-latch), in a way this book does not need: its behaviour is what matters. A register of $n$ bits is $n$ [flip-flops](#def-g11-gates-to-arithmetic-unit-latch) that share the same clock.

```python
class DFlipFlop:
    """Copies its input D to its output Q at a rising edge of the clock, only then."""

    def __init__(self):
        self.q = 0
        self.clock = 0

    def update(self, d, clock):
        if self.clock == 0 and clock == 1:  # rising edge
            self.q = d
        self.clock = clock


register = [DFlipFlop() for _ in range(4)]  # a 4-bit register
inputs = [0b0101, 0b0101, 0b1100, 0b1100, 0b1111, 0b0011, 0b0011, 0b1000]
clocks = [0, 1, 1, 0, 0, 1, 0, 1]
for t, (d, clock) in enumerate(zip(inputs, clocks)):
    for i, ff in enumerate(register):
        ff.update((d >> i) & 1, clock)
    q = sum(ff.q << i for i, ff in enumerate(register))
    print(f"t={t}  D={d:04b}  clock={clock}  Q={q:04b}")
```

***Listing 12.7.** A $4$-bit register of D [flip-flops](#def-g11-gates-to-arithmetic-unit-latch), described by their behaviour. code/grade-11/01-gates-to-arithmetic-unit/listings/dff_register.py*

```
$ python dff_register.py
t=0  D=0101  clock=0  Q=0000
t=1  D=0101  clock=1  Q=0101
t=2  D=1100  clock=1  Q=0101
t=3  D=1100  clock=0  Q=0101
t=4  D=1111  clock=0  Q=0101
t=5  D=0011  clock=1  Q=0011
t=6  D=0011  clock=0  Q=0011
t=7  D=1000  clock=1  Q=1000
```

***Output 12.7.** $Q$ changes only at $t = 1$, $5$ and $7$, the rising edges: the input $1100$ at $t = 2$ and $3$ is never stored.*

**Remark 12.8.**

A processor is these pieces put together: registers of [flip-flops](#def-g11-gates-to-arithmetic-unit-latch) hold the numbers, an ALU computes from two of them, [multiplexers](#def-g11-gates-to-arithmetic-unit-mux) and [decoders](#def-g11-gates-to-arithmetic-unit-mux) choose which, and the clock makes every [flip-flop](#def-g11-gates-to-arithmetic-unit-latch) take its new value at the same moment, once the slowest path through the [combinational circuits](#def-g11-gates-to-arithmetic-unit-combinational) has settled. The length of that path fixes how fast the clock may beat; the next chapter assembles the whole machine.

## 12.6 Exercises

**Exercise 12.1 ★.**

Give the outputs of the [full adder](#def-g11-gates-to-arithmetic-unit-full-adder) for $a = 1$, $b = 0$, $c = 1$, and the values of $p$ and $g$ in the figure of the [full adder](#def-g11-gates-to-arithmetic-unit-full-adder).

**Solution of Exercise 12.1.**

$p = 1 \oplus 0 = 1$ and $g = 1 \wedge 0 = 0$; then $s = p \oplus c = 0$ and the second carry is $p \wedge c = 1$, so $c' = 0 \vee 1 = 1$. Indeed $1 + 0 + 1 = 2$, written $10$.

**Exercise 12.2 ★.**

Add $0111$ and $0110$ through a $4$-bit [ripple-carry adder](#def-g11-gates-to-arithmetic-unit-ripple), column by column: list the carries $c_0$ to $c_4$ and the sum bits.

**Solution of Exercise 12.2.**

$c_0 = 0$. Column $0$: $1 + 0 + 0 = 1$, so $s_0 = 1$, $c_1 = 0$. Column $1$: $1 + 1 + 0 = 2$, so $s_1 = 0$, $c_2 = 1$. Column $2$: $1 + 1 + 1 = 3$, so $s_2 = 1$, $c_3 = 1$. Column $3$: $0 + 0 + 1 = 1$, so $s_3 = 1$, $c_4 = 0$. The sum is $1101$, that is $7 + 6 = 13$.

**Exercise 12.3 ★.**

The inputs of a $4{:}1$ [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) are $x_0 = 1$, $x_1 = 0$, $x_2 = 0$, $x_3 = 1$. What is the output for each of the four values of $s_1 s_0$?

**Solution of Exercise 12.3.**

$s_1 s_0 = 00$ gives $x_0 = 1$, $01$ gives $x_1 = 0$, $10$ gives $x_2 = 0$, $11$ gives $x_3 = 1$.

**Exercise 12.4 ★.**

A [decoder](#def-g11-gates-to-arithmetic-unit-mux) has $3$ input bits. How many outputs does it have, and which one is $1$ when the inputs are $101$?

**Solution of Exercise 12.4.**

$2^3 = 8$ outputs, numbered $0$ to $7$; for $101$ the output number $5$ is $1$ and the seven others are $0$.

**Exercise 12.5 ★.**

Write `half_adder(a, b)` using only `NOT`, `AND` and `OR`, and check it on its four rows.

**Solution of Exercise 12.5.**

The carry is `AND(a, b)`; the sum is $1$ when at least one input is $1$ but not both, so it is `AND(OR(a, b), NOT(AND(a, b)))`. The file `exercises/circuits.py` has it, and the tests check the four rows.

**Exercise 12.6 ★★.**

In a [full adder](#def-g11-gates-to-arithmetic-unit-full-adder), the first half adder was built with an AND gate where its XOR should be. On which of the eight rows is the result wrong? Which test of the chapter would find it?

**Solution of Exercise 12.6.**

Six rows are wrong: every row except $000$ and $001$. With an AND, the first “sum” is $1$ only when $a = b = 1$, so it is wrong whenever exactly one of $a$, $b$ is $1$ (four rows); and when $a = b = 1$, the first “sum” is $1$ instead of $0$, so the sum bit becomes $1 \oplus c$, the opposite of $c$, wrong in both rows (the carry, $ab$, stays right). The `assert` of `full_adder.py`, which tries all eight rows, stops at the third, $010$.

**Exercise 12.7 ★★.**

Write `mux4(sel, inputs)`, where `sel` is a whole number from $0$ to $3$ and `inputs` a list of four bits, using `mux2` only.

**Solution of Exercise 12.7.**

Split `sel` into its two bits, then choose within each pair and between the pairs:

    `s1, s0 = (sel >> 1) & 1, sel & 1`

    `low = mux2(s0, inputs[0], inputs[1])`

    `high = mux2(s0, inputs[2], inputs[3])`

and the result is `mux2(s1, low, high)`. The file `exercises/circuits.py` writes the three calls as one expression.

**Exercise 12.8 ★★.**

How many gates does an $n$-bit [ripple-carry adder](#def-g11-gates-to-arithmetic-unit-ripple) have? How many if the first column, whose carry in is always $0$, uses a half adder?

**Solution of Exercise 12.8.**

Five gates per [full adder](#def-g11-gates-to-arithmetic-unit-full-adder): $5n$. With a half adder (two gates) in the first column: $5(n - 1) + 2 = 5n - 3$.

**Exercise 12.9 ★★.**

Count the gates a signal crosses from the carry $c_i$ to the carry $c_{i+1}$ in the figure of the [full adder](#def-g11-gates-to-arithmetic-unit-full-adder). Deduce the length of the longest chain of gates in an $n$-bit [ripple-carry adder](#def-g11-gates-to-arithmetic-unit-ripple), assuming all the inputs are ready at the start.

**Solution of Exercise 12.9.**

From $c_i$ to $c_{i+1}$ the signal crosses the AND of the second half adder and the OR: $2$ gates. In column $0$, the carry $c_1$ needs the XOR, then an AND, then the OR: level $3$. Each later column adds $2$, so $c_n$ is ready at level $3 + 2(n - 1) = 2n + 1$, and that is the longest chain. For $64$ bits, $129$ gates.

**Exercise 12.10 ★★.**

A subtraction circuit flips the bits of $b$ but leaves the first carry at $0$. What does it compute for $100 - 27$? In general?

**Solution of Exercise 12.10.**

It computes $a + \overline{b} = a + (2^n - 1 - b)$, that is $a - b - 1$ modulo $2^n$: $100 - 27$ gives $72$ instead of $73$. Every result is one too small.

**Exercise 12.11 ★★.**

Write `alu_reference(op, x, y)`, which computes the same result and [flags](#def-g11-gates-to-arithmetic-unit-flag) as the ALU with Python’s integer operators instead of gates. Why is such a second version useful?

**Solution of Exercise 12.11.**

For ADD, the result is `(x + y) % 256` and $C$ is `int(x + y > 255)`; for SUB, `(x - y) % 256` and `int(x < y)`; $Z$ is `int(r == 0)` and $N$ is `r >> 7` (`exercises/circuits.py`). Two versions written in very different ways rarely make the same mistake: comparing them on many inputs finds the mistakes of either. The tests compare the gate ALU with this one and with the toy machine.

**Exercise 12.12 ★★★.**

From the truth table of the [full adder](#def-g11-gates-to-arithmetic-unit-full-adder), prove that $s = a \oplus b \oplus c$ and that $c' = (a \wedge b) \vee (c \wedge (a \oplus b))$, then that $c'$ is also $(a \wedge b) \vee (b \wedge c) \vee
(a \wedge c)$: the carry is $1$ when at least two inputs are.

**Solution of Exercise 12.12.**

The table shows $s = 1$ exactly on the rows with one or three ones, an odd number; $a \oplus b$ is $1$ when $a + b$ is odd, and XOR with $c$ flips that when $c = 1$, so $a \oplus b \oplus c$ is $1$ exactly when $a + b + c$ is odd: $s = a \oplus b \oplus c$. The table shows $c' = 1$ exactly on the rows $011$, $101$, $110$, $111$, those with at least two ones. The term $a \wedge b$ is $1$ on $110$ and $111$; the term $c \wedge (a \oplus b)$ on $011$ and $101$; their OR is $1$ on these four rows and no other. The three terms $a \wedge b$, $b \wedge c$, $a \wedge c$ say “these two are $1$”, and their OR is $1$ exactly when at least two inputs are: the same four rows.

**Exercise 12.13 ★★★.**

Let $\overline{b}$ be $b$ with its $n$ bits flipped. Prove that $\overline{b} = 2^n - 1 - b$, then that $a + \overline{b} + 1 \equiv a - b \pmod{2^n}$, and that the carry out of this sum is $1$ exactly when $a \ge b$.

**Solution of Exercise 12.13.**

Bit $i$ of $\overline{b}$ is $1 - b_i$, so $\overline{b} = \sum_i (1 - b_i) 2^i = (2^n - 1) - b$. Then $a + \overline{b} + 1 = a - b + 2^n$, which is $a - b$ modulo $2^n$. The adder keeps $n$ bits, and its carry out is $1$ exactly when the true sum $a - b + 2^n$ is at least $2^n$, that is when $a \ge b$.

**Exercise 12.14 ★★★.**

Write `comparator(x, y)`, which returns `"<"`, `"="` or `">"` for two numbers without sign, using only the result and the carry out of the subtraction circuit.

**Solution of Exercise 12.14.**

Subtract $y$ from $x$. If the result is $0$, `"="`; otherwise, a carry out of $0$ means a borrow, so $x < y$ and the answer is `"<"`; a carry out of $1$ means $x > y$ (`exercises/circuits.py`). These are the [flags](#def-g11-gates-to-arithmetic-unit-flag) $Z$ and $C$ of the instruction `CMP` of the toy machine.

**Exercise 12.15 ★★★.**

Trace the SR [latch](#def-g11-gates-to-arithmetic-unit-latch) by hand, both gates updated at once, from $Q = 0$, $\overline{Q} = 1$: first $S = R = 1$ until it settles, then $S = R = 0$. Then trace the same release when the gate of $Q$ is faster, so that it updates first. Explain why the inputs $S = R = 1$ are forbidden.

**Solution of Exercise 12.15.**

With $S = R = 1$, from $(Q, \overline{Q}) = (0, 1)$: both NORs see a $1$, so the next state is $(0, 0)$, and it stays. Releasing both at once, each gate sees two zeros: $(1, 1)$; then each sees a $1$: $(0, 0)$; and so on for ever, as the output of `latch.py` shows. If the gate of $Q$ is faster, it switches first to $Q = \text{NOR}(0, 0) = 1$; the other gate then sees $Q = 1$ and stays at $0$: the [latch](#def-g11-gates-to-arithmetic-unit-latch) ends at $Q = 1$. If the other gate is faster, it ends at $Q = 0$. The final state depends on which gate is faster, which nobody controls; and while $S = R = 1$, $\overline{Q}$ is not the opposite of $Q$. Both are reasons to forbid these inputs.

## 12.7 Problem: Building a 64-Bit Adder

**Problem 12.1.**

Weekend problem — the size and the speed of an adder

A processor adds numbers of $64$ bits. How many gates does its adder need, and how long is the longest chain of gates a signal must cross before the sum is ready? The program `gate_count.py` answers by running the adders of the chapter on *levels* instead of bits: each signal carries the number of gates it has crossed since the inputs.

```python
"""Count the gates of an adder, and the longest chain of gates a signal goes through."""

count = 0


def gate(*inputs):
    """A gate seen from outside: its output is ready one level after its last input."""
    global count
    count += 1
    return max(inputs) + 1


def full_adder(a, b, c):  # the same five gates as full_adder.py, on levels
    p = gate(a, b)                      # XOR
    s = gate(p, c)                      # XOR
    carry = gate(gate(a, b), gate(p, c))  # OR of two ANDs
    return s, carry


def ripple(n, carry=0):
    sums = []
    for _ in range(n):
        s, carry = full_adder(0, 0, carry)  # the inputs are ready at level 0
        sums.append(s)
    return sums, carry


def carry_select(n):
    """The low half ripples; the high half is computed twice, for carry 0 and 1."""
    low, c = ripple(n // 2)
    high0, c0 = ripple(n // 2, 0)  # assuming carry 0
    high1, c1 = ripple(n // 2, 0)  # assuming carry 1: a constant too, at level 0
    not_c = gate(c)
    chosen = [gate(gate(not_c, x0), gate(c, x1))  # a 2:1 multiplexer per bit
              for x0, x1 in zip(high0 + [c0], high1 + [c1])]
    return low + chosen[:-1], chosen[-1]
```

***Listing 12.8.** Gates that count themselves and their levels, and two adders built from them. code/grade-11/01-gates-to-arithmetic-unit/listings/gate_count.py*

```
$ python gate_count.py
   n | ripple: gates levels | carry-select: gates levels
   2 |            10      5 |                  22      6
   4 |            20      9 |                  40      8
   8 |            40     17 |                  76     12
  16 |            80     33 |                 148     20
  32 |           160     65 |                 292     36
  64 |           320    129 |                 580     68
```

***Output 12.8.** The count and the depth of the two adders.*

**Part I — One full adder.**

1. In `gate_count.py` , what does `gate` return, and why is the maximum of the inputs the right choice?
2. Check that its `full_adder` uses the same five gates as the figure of the [full adder](#def-g11-gates-to-arithmetic-unit-full-adder) .
3. With all three inputs at level $0$ , at which level are $s$ and the carry out ready?
4. With $a$ and $b$ at level $0$ and the carry in at level $k \ge 1$ , at which levels are $s$ and the carry out ready?

**Part II — The ripple-carry adder.**

5. Show that the carry gains two levels at each column after the first, and deduce that $c_i$ is ready at level $2i + 1$ , for $i \ge 1$ .
6. Deduce the level of the last sum bit and of the carry out, for $n$ bits, and check them against the output.
7. How many gates for $8$ , $16$ , $32$ and $64$ bits?
8. If a gate takes $10$ picoseconds to switch, how long does a $64$ -bit ripple-carry addition take, and how many such additions could follow each other in one second?
9. Which part of the circuit decides that time: the sum bits or the carry chain?

**Part III — Carry-select.**

10. The carry-select adder adds the low half with a ripple adder. Explain why the high half can be computed before the carry of the low half is known.
11. Why is it computed twice, and how is the right copy chosen?
12. In the program, how many $2{:}1$ [multiplexers](#def-g11-gates-to-arithmetic-unit-mux) are used for $n$ bits, and how many gates does each take?
13. Compute the number of gates of the carry-select adder for $n$ bits, and check it for $n = 64$ .
14. At which level is the carry of the low half ready, and at which level is the output of a [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) ready?
15. Check the depth of $68$ for $64$ bits.

**Part IV — Comparing.**

16. For $64$ bits, compute the ratio of the gates and the ratio of the levels of the two adders.
17. Split the $64$ bits into four blocks of $16$ instead of two halves, each block after the first computed twice. Estimate its depth.
18. Why do processors pay for more gates to save levels?
19. Is there a limit to the speed-up? Describe the shortest adder you can imagine, and what it costs.
20. State the result: the gates and levels of a $64$ -bit [ripple-carry adder](#def-g11-gates-to-arithmetic-unit-ripple) , and what carry-select buys and costs.

**Solution of Problem 12.1.**

**1.** The level of its output: one more than the latest of its inputs, since a gate can only switch once all its inputs are there.

**2.** `p` is the XOR of $a$ and $b$, `s` the XOR of `p` and $c$, then two ANDs, of $a$ and $b$ and of `p` and $c$, and the OR of these: five gates, as in the figure.

**3.** $p$ at $1$, $s$ at $2$; the ANDs at $1$ and $2$, the carry out at $3$.

**4.** $p$ at $1$, $s$ at $k + 1$; the AND of $a$ and $b$ at $1$, the AND of $p$ and $c$ at $k + 1$, and the carry out at $k + 2$.

**5.** By question 3, $c_1$ is at level $3$; by question 4, a carry at level $k$ gives the next one at $k + 2$. So $c_1, c_2, c_3, \dots$ are at $3, 5, 7, \dots$: $c_i$ is at $2i + 1$.

**6.** The last sum bit $s_{n-1}$ is at $(2(n - 1) + 1) + 1 = 2n$, the carry out $c_n$ at $2n + 1$. The output gives $5$ for $2$ bits and $129$ for $64$: $2n + 1$, the carry out being the last signal ready.

**7.** $5n$: $40$, $80$, $160$ and $320$ gates.

**8.** $129 \times 10$ ps $= 1.29$ ns, so about $775$ million additions in a row per second.

**9.** The carry chain: each sum bit is ready one level after its carry, so the sums wait for the carries.

**10.** Its inputs, the high halves of $A$ and $B$, are there from the start; only its carry in is missing, and that carry can only be $0$ or $1$.

**11.** Once assuming a carry of $0$, once assuming $1$; when the low half’s carry arrives, a [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) per output bit keeps the copy made with the right assumption.

**12.** One [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) per sum bit of the high half and one for the carry out: $n/2 + 1$. Each takes two ANDs and an OR, and the NOT of the select signal is shared by all.

**13.** Three ripple adders of $n/2$ bits, $3 \times 5n/2$ gates, plus $3(n/2 + 1)$ for the [multiplexers](#def-g11-gates-to-arithmetic-unit-mux) and $1$ NOT: $15n/2 + 3n/2 + 4 = 9n + 4$. For $n = 64$, $580$, as printed.

**14.** The low half is a ripple adder of $n/2$ bits: its carry is at level $2(n/2) + 1 = n + 1$. The high halves are ready earlier, at level $n + 1$ at most. The NOT of the carry is at $n + 2$, the AND that uses it at $n + 3$, the OR at $n + 4$.

**15.** $64 + 4 = 68$.

**16.** $580/320 \approx 1.81$ times the gates, for $68/129 \approx 0.53$ times the levels.

**17.** The first block of $16$ bits gives its carry at level $33$. The three other blocks are computed both ways in parallel, and ready at level $33$ too. Each [multiplexer](#def-g11-gates-to-arithmetic-unit-mux) stage adds $3$ levels to the chosen carry: $36$ after the second block, $39$ after the third, and the outputs of the last block at about $42$. The gates grow again, to about $5 \cdot 16 + 3 \cdot 2 \cdot 5 \cdot 16 + 3 \cdot 3 \cdot 17 + 3 \approx 716$.

**18.** Every instruction must finish within one beat of the clock, so the slowest circuit sets the speed of the whole processor. Gates are tiny and cheap, counted in billions on one chip; time is not.

**19.** More blocks, and blocks inside blocks, reduce the depth further: adders used in processors make the depth grow much more slowly than the number of bits, so that doubling the bits adds only a few levels. The shortest imaginable adder writes each output as one OR of ANDs of the inputs, two levels deep, but the cost explodes: for the top carry of $64$ bits, the OR would need on the order of $2^{64}$ AND terms, each with up to $128$ inputs. Speed always costs gates, and two levels cost exponentially many.

**20.** A $64$-bit [ripple-carry adder](#def-g11-gates-to-arithmetic-unit-ripple) needs $320$ gates, five per [full adder](#def-g11-gates-to-arithmetic-unit-full-adder), and its longest chain crosses $129$ gates, the carry gaining two levels per column. A carry-select adder of two halves needs $580$ gates, $1.81$ times as many, and $68$ levels, $0.53$ times as many: it nearly halves the delay for less than twice the gates.
