---
title: "The von Neumann Machine and Assembly Language"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 13
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/13-the-von-neumann-machine-and-assembly-language
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 13 — The von Neumann Machine and Assembly Language

In a computer’s memory, the instruction “add register $2$ to register $1$” and the number $17$ followed by the number $2$ are the same two bytes. The processor cannot tell them apart; it reads whatever its program counter points at, and runs it as an instruction. This single idea, program and data in the same memory, is what makes a computer able to load a new program as easily as new data, and it is also why a wrong write can turn data into code.

This chapter takes the toy machine of Book 1 seriously: its whole [instruction set](#def-g11-von-neumann-machine-instruction-set), programs with [jumps](#def-g11-von-neumann-machine-jump) and loops, the stack and [subroutines](#def-g11-von-neumann-machine-subroutine), and the step from a line of Python down to the machine’s instructions.

**You already know.**

A processor repeats the same cycle: fetch the instruction at the address in the program counter, decode it, execute it. Its registers are a few fast cells inside it; machine language is the numbers that encode its instructions; a chip may hold several cores, each running its own program (Book 1, grade 7). An adder, a [multiplexer](https://one-course.com/books/computer-science/2/en/chapter/12-from-gates-to-an-arithmetic-unit#def-g11-gates-to-arithmetic-unit-mux) and a register of [flip-flops](https://one-course.com/books/computer-science/2/en/chapter/12-from-gates-to-an-arithmetic-unit#def-g11-gates-to-arithmetic-unit-latch) are built from gates (the previous chapter).

## 13.1 Processor, memory, buses

**Definition 13.1 (von Neumann architecture).**

A computer has a *von Neumann architecture* when it is made of a processor (a control unit, an ALU and registers), one memory that holds both the program and its data, and input and output devices, and when the processor runs the program by fetching its instructions from that memory one after the other.

**Definition 13.2 (Bus).**

A *bus* is a set of wires shared by several components to carry one kind of signal. The *address bus* carries the number of the memory cell or device being accessed, the *data bus* the value read or written, and the *control bus* the signals that say what to do and when, such as “read” or “write”.

![The von Neumann model. The processor reaches the memory and the devices through the same three buses; one memory holds the program and its data.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-von-neumann-machine/fig-6ab2e33720b9.svg)

*The von Neumann model. The processor reaches the memory and the devices through the same three buses; one memory holds the program and its data.*

Each fetch, each `LOAD` and each `STORE` is a trip over the buses: the processor puts an address on the address [bus](#def-g11-von-neumann-machine-bus) and “read” on the control [bus](#def-g11-von-neumann-machine-bus), and the memory answers on the data [bus](#def-g11-von-neumann-machine-bus). A machine with several processors, or several cores, has them share the memory in the same way, each running its own instructions.

**History — A report and a baby.**

In 1945, the mathematician John von Neumann circulated a *First Draft of a Report on the EDVAC*, which described a computer keeping its program in the same electronic memory as its data, instead of on plugboards or punched tape.

The first machine to run such a stored program was built in Manchester, England, by Freddie Williams, Tom Kilburn and Geoff Tootill: nicknamed the Baby, it ran its first program, $17$ instructions written by Kilburn to find the largest factor of a number, on 21 June 1948.

![A replica of the Baby on display in Manchester: racks of valves, and in the middle the small screen that showed its memory. Photograph: KGGucwa, CC BY-SA 3.0.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-von-neumann-machine/img-b81d048ad627.jpg)

*A replica of the Baby on display in Manchester: racks of valves, and in the middle the small screen that showed its memory. Photograph: KGGucwa, CC BY-SA 3.0.*

## 13.2 The toy machine in full

Book 1 traced small programs of the toy machine by hand. Its full description is short: $256$ cells of one byte, four registers `R0` to `R3`, a program counter `PC`, a [stack pointer](#def-g11-von-neumann-machine-subroutine) `SP`, and the three flags of the previous chapter. Arithmetic wraps modulo $256$.

**Definition 13.3 (Instruction set).**

The *instruction set* of a processor is the list of the instructions it can execute, with their encoding in bytes and their exact effect on registers, flags and memory.

The toy machine has $28$ instructions. Each takes two bytes: the first holds a $6$-bit operation code and a $2$-bit register number, the second an operand: a number, an address, or a second register.

| 0 | `HALT` | 10 | `NOT r` | 20 | `OUT r` |
| --- | --- | --- | --- | --- | --- |
| 1 | `LOADI r, n` | 11 | `SHL r` | 21 | `LOADR r, s` |
| 2 | `LOAD r, [a]` | 12 | `SHR r` | 22 | `STORER r, s` |
| 3 | `STORE r, [a]` | 13 | `CMP r, s` | 23 | `PUSH r` |
| 4 | `ADD r, s` | 14 | `JMP a` | 24 | `POP r` |
| 5 | `SUB r, s` | 15 | `JZ a` | 25 | `CALL a` |
| 6 | `ADDI r, n` | 16 | `JNZ a` | 26 | `RET` |
| 7 | `AND r, s` | 17 | `JN a` | 27 | `NOP` |
| 8 | `OR r, s` | 18 | `JC a` |  |  |
| 9 | `XOR r, s` | 19 | `IN r` |  |  |

`LOADI` puts a number in a register, `LOAD` and `STORE` move a byte between a register and a cell, and `LOADR` and `STORER` do the same with the address in a register. The arithmetic and logic instructions, and `CMP`, which subtracts without keeping the result, set the flags $Z$, $N$ and $C$.

![The encoding of an instruction: the first byte is 4 × operation code + r. Below, ADD R1, R2: the bytes 4 × 4 + 1 = 17 and 2.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-von-neumann-machine/fig-70ec76688118.svg)

*The encoding of an instruction: the first byte is $4 \times \text{operation code} + r$. Below, `ADD R1, R2`: the bytes $4 \times 4 + 1 = 17$ and $2$.*

The step of the machine refines the cycle of Book 1: fetch the two bytes at `PC` and `PC + 1`, add $2$ to `PC`, decode, execute. A [jump](#def-g11-von-neumann-machine-jump) writes a new address into `PC` after that increment, so the next fetch happens there.

## 13.3 Assembly programs with jumps

**Definition 13.4 (Assembly language, assembler, label).**

An *assembly language* writes a machine’s instructions with names instead of numbers, one instruction per line. A *label* is a name given to the address of a line, so that other instructions can refer to it. An *assembler* is the program that translates assembly language into machine code, replacing every name and every label by its number.

**Definition 13.5 (Jump, conditional jump).**

A *jump* writes an address into the program counter, so that execution goes on there. A *conditional jump* does so only if a flag has a given value (`JZ` if $Z = 1$, `JNZ` if $Z = 0$, `JN` if $N = 1$, `JC` if $C = 1$), and otherwise lets execution go on to the next instruction.

Conditions and loops are built from these. `CMP R0, R1` computes $R_0 - R_1$ and sets $C$ when it needs a borrow, that is when $R_0 < R_1$ for numbers without sign: `JC` after a `CMP` means “[jump](#def-g11-von-neumann-machine-jump) if smaller”.

```text
; max2.toy -- reads two numbers, prints the larger
        IN    R0
        IN    R1
        CMP   R0, R1      ; R0 - R1: C = 1 when R0 < R1
        JC    second
        OUT   R0
        HALT
second: OUT   R1
        HALT
```

***Listing 13.1.** An *if*: the larger of two numbers. code/grade-11/02-von-neumann-machine/listings/max2.toy*

```
$ python -m toymachine run max2.toy
201
```

***Output 13.1.** With the inputs $57$ and $201$, from `max2.stdin`.*

A loop is a [jump](#def-g11-von-neumann-machine-jump) backwards. The option `--trace` prints a row before each step: the step number, `PC`, the instruction, the four registers and the three flags.

```text
; count_down.toy -- prints 3, 2, 1
; capture: args=--trace
        LOADI R0, 3
        LOADI R1, 1
loop:   OUT   R0
        SUB   R0, R1      ; sets Z when R0 reaches 0
        JNZ   loop
        HALT
```

***Listing 13.2.** A loop: a counter, a subtraction that sets $Z$, a [jump](#def-g11-von-neumann-machine-jump) back while $Z = 0$. code/grade-11/02-von-neumann-machine/listings/count_down.toy*

```
$ python -m toymachine run count_down.toy --trace
step  PC  instruction       R0  R1  R2  R3  Z N C
   1   0  LOADI R0, 3        0   0   0   0  0 0 0
   2   2  LOADI R1, 1        3   0   0   0  0 0 0
   3   4  OUT R0             3   1   0   0  0 0 0
3
   4   6  SUB R0, R1         3   1   0   0  0 0 0
   5   8  JNZ 4              2   1   0   0  0 0 0
   6   4  OUT R0             2   1   0   0  0 0 0
2
   7   6  SUB R0, R1         2   1   0   0  0 0 0
   8   8  JNZ 4              1   1   0   0  0 0 0
   9   4  OUT R0             1   1   0   0  0 0 0
1
  10   6  SUB R0, R1         1   1   0   0  0 0 0
  11   8  JNZ 4              0   1   0   0  1 0 0
  12  10  HALT               0   1   0   0  1 0 0
halted after 12 steps
```

***Output 13.2.** The trace: `JNZ 4` [jumps](#def-g11-von-neumann-machine-jump) back to address $4$ until the subtraction reaches $0$ (step $11$, $Z = 1$).*

![The flow of the loop, with the address of each instruction. The label loop is the number 4; the assembler writes JNZ 4. When Z = 1, execution goes on to the next line, HALT.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-von-neumann-machine/fig-80177cd81dcd.svg)

*The flow of the loop, with the address of each instruction. The [label](#def-g11-von-neumann-machine-assembly) `loop` is the number $4$; the [assembler](#def-g11-von-neumann-machine-assembly) writes `JNZ 4`. When $Z = 1$, execution goes on to the next line, `HALT`.*

The data of a program can sit in memory right after its code: `DATA` places bytes there, and a [label](#def-g11-von-neumann-machine-assembly) gives their address. With an address in a register, `LOADR` reads a cell chosen at run time, which is how a loop walks through an array.

```text
; sum_array.toy -- adds the numbers of an array stored after the program
        LOADI R0, 0         ; the total
        LOADI R1, array     ; address of the next number
        LOAD  R2, [length]  ; how many are left
loop:   LOADR R3, R1        ; R3 = M[R1]
        ADD   R0, R3
        ADDI  R1, 1
        ADDI  R2, -1        ; Z when none is left
        JNZ   loop
        OUT   R0
        HALT
length: DATA  6
array:  DATA  12, 7, 30
        DATA  1, 25, 9
```

***Listing 13.3.** An array in memory, and a loop that adds it up. code/grade-11/02-von-neumann-machine/listings/sum_array.toy*

```
$ python -m toymachine run sum_array.toy
84
```

***Output 13.3.** $12 + 7 + 30 + 1 + 25 + 9 =
84$.*

The [assembler](#def-g11-von-neumann-machine-assembly) shows what the program becomes: for each line, its address, its two bytes in decimal and in binary, and the source.

```
$ python -m toymachine asm sum_array.toy
  0:   4   0  00000100 00000000  LOADI R0, 0         ; the total
  2:   5  21  00000101 00010101  LOADI R1, array     ; address of the next number
  4:  10  20  00001010 00010100  LOAD  R2, [length]  ; how many are left
  6:  87   1  01010111 00000001  loop:   LOADR R3, R1        ; R3 = M[R1]
  8:  16   3  00010000 00000011  ADD   R0, R3
 10:  25   1  00011001 00000001  ADDI  R1, 1
 12:  26 255  00011010 11111111  ADDI  R2, -1        ; Z when none is left
 14:  64   6  01000000 00000110  JNZ   loop
 16:  80   0  01010000 00000000  OUT   R0
 18:   0   0  00000000 00000000  HALT
 20:   6      00000110           length: DATA  6
 21:  12   7  30 00001100 00000111 00011110  array:  DATA  12, 7, 30
 24:   1  25   9 00000001 00011001 00001001  DATA  1, 25, 9
```

***Output 13.4.** The machine code of `sum_array.toy`. The [label](#def-g11-von-neumann-machine-assembly) `array` became $21$ and `loop` became $6$; the `DATA` lines take one byte per number.*

![The memory of sum_array.toy: ten instructions in cells 0 to 19, the data in 20 to 26. A program that uses the stack fills it from cell 255 down, towards the code.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-von-neumann-machine/fig-b1825c022e17.svg)

*The memory of `sum_array.toy`: ten instructions in cells $0$ to $19$, the data in $20$ to $26$. A program that uses the stack fills it from cell $255$ down, towards the code.*

Negative numbers are stored 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); `IN` reads $-42$ as $256 - 42 = 214$. The flag $N$ tells a negative result, and `JN` acts on it.

```text
; abs_value.toy -- reads a number from -128 to 127, prints its absolute value
        IN    R0
        ADDI  R0, 0         ; adds nothing, but sets N from bit 7
        JN    negative
        OUT   R0
        HALT
negative:
        NOT   R0            ; two's complement: flip every bit...
        ADDI  R0, 1         ; ...and add 1
        OUT   R0
        HALT
```

***Listing 13.4.** The absolute value: `NOT` and `ADDI 1` negate a number. code/grade-11/02-von-neumann-machine/listings/abs_value.toy*

```
$ python -m toymachine run abs_value.toy
42
```

***Output 13.5.** With the input $-42$.*

The toy machine has no multiplication. A loop adds $a$ to a total $b$ times; the weekend problem measures its cost and finds a much faster way.

```text
; multiply.toy -- reads a and b, prints a * b by adding a, b times
        IN    R0            ; a
        IN    R1            ; b, the number of additions left
        LOADI R2, 0         ; the product
        LOADI R3, 1
        ADDI  R1, 0         ; sets Z if b is 0
        JZ    done
loop:   ADD   R2, R0
        SUB   R1, R3
        JNZ   loop
done:   OUT   R2
        HALT
```

***Listing 13.5.** Multiplication by repeated addition. code/grade-11/02-von-neumann-machine/listings/multiply.toy*

```
$ python -m toymachine run multiply.toy
143
```

***Output 13.6.** $13 \times 11$, from `multiply.stdin`.*

## 13.4 Subroutines and the stack

A piece of code used in several places is written once, as a [subroutine](#def-g11-von-neumann-machine-subroutine), and called. The difficulty is to come back: the [subroutine](#def-g11-von-neumann-machine-subroutine) must know where it was called from.

**Definition 13.6 (Subroutine, stack pointer).**

A *subroutine* is a sequence of instructions that is entered by `CALL` and left by `RET`. The *stack pointer* `SP` holds the address of the top of a zone of memory, the stack, used last in, first out: `PUSH r` lowers `SP` by one and stores `r` there, `POP r` reads it back and raises `SP`. `CALL a` pushes the address of the next instruction and [jumps](#def-g11-von-neumann-machine-jump) to `a`; `RET` pops an address into `PC`.

The stack starts at the top of memory: `SP` is $0$ at the start, so the first `PUSH` writes cell $255$. A [subroutine](#def-g11-von-neumann-machine-subroutine) that uses a register the caller needs saves it with `PUSH` and gives it back with `POP` before returning.

```text
; call_square.toy -- a subroutine that squares R0 into R1
; capture: args=--trace
        LOADI R0, 3
        CALL  square        ; pushes the return address 4, jumps
        OUT   R1
        HALT
square: PUSH  R2            ; keep the caller's R2
        LOADI R1, 0
        LOADI R2, 0
        ADD   R2, R0        ; R2 = R0 additions to do
again:  ADD   R1, R0
        ADDI  R2, -1
        JNZ   again
        POP   R2            ; give R2 back
        RET                 ; pops 4 into PC
```

***Listing 13.6.** A [subroutine](#def-g11-von-neumann-machine-subroutine) that squares `R0`, and keeps the caller’s `R2`. code/grade-11/02-von-neumann-machine/listings/call_square.toy*

```
$ python -m toymachine run call_square.toy --trace
step  PC  instruction       R0  R1  R2  R3  Z N C
   1   0  LOADI R0, 3        0   0   0   0  0 0 0
   2   2  CALL 8             3   0   0   0  0 0 0
   3   8  PUSH R2            3   0   0   0  0 0 0
   4  10  LOADI R1, 0        3   0   0   0  0 0 0
   5  12  LOADI R2, 0        3   0   0   0  0 0 0
   6  14  ADD R2, R0         3   0   0   0  0 0 0
   7  16  ADD R1, R0         3   0   3   0  0 0 0
   8  18  ADDI R2, 255       3   3   3   0  0 0 0
   9  20  JNZ 16             3   3   2   0  0 0 1
  10  16  ADD R1, R0         3   3   2   0  0 0 1
  11  18  ADDI R2, 255       3   6   2   0  0 0 0
  12  20  JNZ 16             3   6   1   0  0 0 1
  13  16  ADD R1, R0         3   6   1   0  0 0 1
  14  18  ADDI R2, 255       3   9   1   0  0 0 0
  15  20  JNZ 16             3   9   0   0  1 0 1
  16  22  POP R2             3   9   0   0  1 0 1
  17  24  RET                3   9   0   0  1 0 1
  18   4  OUT R1             3   9   0   0  1 0 1
9
  19   6  HALT               3   9   0   0  1 0 1
halted after 19 steps
```

***Output 13.7.** Step $2$ pushes $4$, the address after the `CALL`; step $17$ pops it, and the program goes on at `OUT R1`.*

During the call, cell $255$ holds the return address $4$ and cell $254$ the saved `R2`. `POP R2` takes back the last value pushed, the saved register, which leaves the return address on top for `RET`. Every `PUSH` needs its `POP` before the `RET`; a missing one makes `RET` [jump](#def-g11-von-neumann-machine-jump) to whatever value is on top. The stack and its uses are a chapter of their own in grade 12.

Since program and data share the memory, nothing stops a program from writing over its own instructions. Here a number meant as data lands on the code:

```text
; self_modify.toy -- a number written over an instruction
; capture: args=--trace
        LOADI R0, 80        ; just a number...
        STORE R0, [stop]    ; ...stored at an address that holds code
        LOADI R1, 7
stop:   HALT                ; the byte 80 is 4 x 20 + 0: OUT R0
        HALT
```

***Listing 13.7.** A store into the code. code/grade-11/02-von-neumann-machine/listings/self_modify.toy*

```
$ python -m toymachine run self_modify.toy --trace
step  PC  instruction       R0  R1  R2  R3  Z N C
   1   0  LOADI R0, 80       0   0   0   0  0 0 0
   2   2  STORE R0, [6]     80   0   0   0  0 0 0
   3   4  LOADI R1, 7       80   0   0   0  0 0 0
   4   6  OUT R0            80   7   0   0  0 0 0
80
   5   8  HALT              80   7   0   0  0 0 0
halted after 5 steps
```

***Output 13.8.** The `HALT` at address $6$ has become `OUT R0`: the machine runs the number $80$ as an instruction.*

**Safe use.**

A program that writes outside its data can change what the machine does next. Attacks on real software have used this for decades: send more data than a buffer holds, let it overwrite code or a return address on the stack, and the processor runs the attacker’s bytes. Modern systems mark memory pages as either writable or executable, never both, to stop it.

## 13.5 From a line of Python to the machine

A compiler translates an *if* or a *while* into tests and [jumps](#def-g11-von-neumann-machine-jump), as this chapter did by hand. The loop `while n > 0: n = n - 1` becomes: a [label](#def-g11-von-neumann-machine-assembly); a comparison of `n` with $0$; a [conditional jump](#def-g11-von-neumann-machine-jump) past the loop when the condition is false; the body; and a [jump](#def-g11-von-neumann-machine-jump) back to the [label](#def-g11-von-neumann-machine-assembly).

Python itself does not run on the processor directly. It first translates a function into the instructions of another machine, simple enough to be run by a program: its *bytecode*. The module `dis` shows them.

```python
import dis


def count_down(n):
    while n > 0:
        n = n - 1
    return n


dis.dis(count_down)
```

***Listing 13.8.** Asking Python for the instructions of a function. code/grade-11/02-von-neumann-machine/listings/py_dis.py*

```
$ python py_dis.py
  4           0 RESUME                   0

  5           2 LOAD_FAST                0 (n)
              4 LOAD_CONST               1 (0)
              6 COMPARE_OP              68 (>)
             10 POP_JUMP_IF_FALSE       11 (to 34)

  6     >>   12 LOAD_FAST                0 (n)
             14 LOAD_CONST               2 (1)
             16 BINARY_OP               10 (-)
             20 STORE_FAST               0 (n)

  5          22 LOAD_FAST                0 (n)
             24 LOAD_CONST               1 (0)
             26 COMPARE_OP              68 (>)
             30 POP_JUMP_IF_FALSE        1 (to 34)
             32 JUMP_BACKWARD           11 (to 12)

  7     >>   34 LOAD_FAST                0 (n)
             36 RETURN_VALUE
```

***Output 13.9.** The bytecode of `count_down`: the left column is the line of the source, the next the address of the instruction.*

The shape is the toy machine’s: loads, a comparison, `POP_JUMP_IF_FALSE` out of the loop, the body, a [jump](#def-g11-von-neumann-machine-jump) back. One difference: Python copies the test to the bottom of the loop (addresses $22$ to $30$), and its [jump](#def-g11-von-neumann-machine-jump) back goes to the body, at $12$, not to the first test; the first test runs only once, before the first turn. Bytecode is an internal detail of Python, which changes from one version to the next; this output comes from Python 3.12.

**Definition 13.7 (System on a chip).**

A *system on a chip* is a single chip that gathers what used to be separate components: processor cores, memory caches, a graphics processor, a memory controller, radios, controllers for the devices, and the management of power.

![The blocks of a typical system on a chip, as found in phones and many laptops. Their number and their names vary from one chip to another.](https://one-course.com/images/onecourse/chapters/computer-science-2/g11-von-neumann-machine/fig-c0d7db409f56.svg)

*The blocks of a typical [system on a chip](#def-g11-von-neumann-machine-soc), as found in phones and many laptops. Their number and their names vary from one chip to another.*

Gathering the components on one chip shortens the wires between them: signals travel faster, and moving data costs less energy, which matters for a battery. The price is that nothing can be changed or added afterwards.

## 13.6 Exercises

**Exercise 13.1 ★.**

What does this program print?

    `LOADI R0, 6` `LOADI R1, 9` `SUB R1, R0` `OUT R1` `HALT`

**Solution of Exercise 13.1.**

`R1` becomes $9 - 6 = 3$, and the program prints `3`.

**Exercise 13.2 ★.**

Encode `ADD R1, R2` and `JNZ 6` in two bytes each, in decimal and in binary.

**Solution of Exercise 13.2.**

`ADD R1, R2`: operation code $4$, $r = 1$, so $4 \times 4 + 1 = 17$, then $2$: `00010001 00000010`. `JNZ 6`: operation code $16$, $r = 0$, so $64$, then $6$: `01000000 00000110`.

**Exercise 13.3 ★.**

Decode the bytes $52, 3$ and then $60, 18$.

**Solution of Exercise 13.3.**

$52 = 4 \times 13 + 0$: operation $13$, `CMP`, with $r = 0$ and $s = 3$: `CMP R0, R3`. $60 = 4 \times 15 +
0$: `JZ`, to the address $18$: `JZ 18`.

**Exercise 13.4 ★.**

`R0` holds $5$ and `R1` holds $10$. Give the result and the flags $Z$, $N$, $C$ after `SUB R0, R1`, then after `SUB R1, R0`.

**Solution of Exercise 13.4.**

$5 - 10$ wraps to $256 - 5 = 251$: $Z = 0$, $N = 1$ (bit 7 is $1$, the result read with sign is $-5$), $C = 1$ (a borrow). Starting again from $5$ and $10$, `SUB R1, R0` gives $5$: $Z = 0$, $N = 0$, $C = 0$.

**Exercise 13.5 ★.**

Write `max3.toy`, which reads three numbers and prints the largest.

**Solution of Exercise 13.5.**

Keep the largest in `R0`; read the next number into `R1`, `CMP R0, R1`, and when `JC` shows `R0` smaller, copy `R1` into `R0` (`LOADI R0, 0` then `ADD R0, R1`, since there is no move instruction). The file `exercises/max3.toy` does it; the tests run it on $50$ random triples.

**Exercise 13.6 ★★.**

A student changes `count_down.toy` to start at $7$ and subtract $2$, to print $7$, $5$, $3$, $1$. What happens? Fix it with one more instruction.

**Solution of Exercise 13.6.**

It prints $7$, $5$, $3$, $1$, then $1 - 2$ wraps to $255$, and the odd numbers $255$, $253$, … follow: the counter never reaches $0$, so `JNZ` always [jumps](#def-g11-von-neumann-machine-jump), until the machine stops the program after $10\,000$ steps. The fix is `JC done` right after the `SUB`: the subtraction borrows exactly when the counter was smaller than $2$ (`exercises/count_by_two_fixed.toy`).

**Exercise 13.7 ★★.**

Write `max_array.toy`, which prints the largest number of an array stored with its length after the program.

**Solution of Exercise 13.7.**

As `sum_array.toy`, but with `CMP R0, R3` and `JC` to a block that copies `R3` into `R0` before going on (`exercises/max_array.toy`). On the array $12, 7, 130, 1, 25, 9, 64$ it prints $130$.

**Exercise 13.8 ★★.**

The program `sum.toy` of Book 1 reads $n$, sets a total to $0$ and a register to $1$, then repeats `ADD R1, R0`, `SUB R0, R2`, `JNZ loop`, and finally prints and halts. How many steps does it execute for an input $n \ge 1$? What happens for $n = 0$?

**Solution of Exercise 13.8.**

Three steps before the loop, three per turn, and `OUT` and `HALT`: $3n + 5$. For $n = 0$, the first `SUB` gives $255$ and $Z = 0$: the loop runs $256$ times, adding $0 + 255 + 254 + \dots + 1 = 32\,640$, which modulo $256$ is $128$. The program prints $128$ after $773$ steps. The tests check $3n + 5$ for $n = 1$, $5$, $20$.

**Exercise 13.9 ★★.**

In the trace of `call_square.toy`, give the value of `SP` and the contents of cells $255$ and $254$ after steps $2$, $3$, $16$ and $17$.

**Solution of Exercise 13.9.**

After step $2$ (`CALL`): `SP` $= 255$, cell $255$ holds $4$. After step $3$ (`PUSH R2`): `SP` $= 254$, cell $254$ holds $0$, the caller’s `R2`. After step $16$ (`POP R2`): `SP` $= 255$; cell $254$ still holds $0$, since popping does not erase. After step $17$ (`RET`): `SP` $= 255 + 1$, which wraps to $0$; cell $255$ still holds $4$.

**Exercise 13.10 ★★.**

In a copy of the [subroutine](#def-g11-von-neumann-machine-subroutine), the line `POP R2` has been removed, and the caller had put $40$ in `R2`. What does `RET` do, and what does the program print?

**Solution of Exercise 13.10.**

On top of the stack is the $40$ pushed by `PUSH R2`, not the return address: `RET` pops it and [jumps](#def-g11-von-neumann-machine-jump) to address $40$. That cell is empty, and two bytes $0$ are `HALT`: the program stops there and prints nothing (`exercises/bad_return.toy`; the tests check it). With other values in `R2`, it could have run anything.

**Exercise 13.11 ★★.**

Write `times_ten.toy`, which reads $x$ and prints $10x$ (modulo $256$) with three shifts and additions, writing $10x$ as $8x + 2x$ (the machine has no copy instruction: copying a register takes a `LOADI` of $0$ and an addition).

**Solution of Exercise 13.11.**

`SHL R0` gives $2x$, which is copied into `R1`; two more `SHL R0` give $8x$, and `ADD R0, R1` gives $10x$ (`exercises/times_ten.toy`). All modulo $256$: for $x = 26$, $260 \bmod 256 = 4$.

**Exercise 13.12 ★★★.**

Prove that `shift_multiply.toy`, from the weekend problem, executes exactly $7 + 7L$ steps, where $L$ is the number of bits of $b$ ($L = 0$ for $b = 0$). Deduce a bound that holds for every input.

**Solution of Exercise 13.12.**

Before the loop: `IN`, `IN`, `LOADI`, $3$ steps. Each turn with a bit $1$ runs `ADDI`, `JZ`, `SHR`, `JC` (taken), `ADD`, `SHL`, `JMP`; with a bit $0$, `ADDI`, `JZ`, `SHR`, `JC` (not taken), `JMP next`, `SHL`, `JMP`: $7$ steps either way. Each turn shifts `R1` right by one, so after $L$ turns it is $0$; then `ADDI`, `JZ`, `OUT`, `HALT`: $4$ steps. In all $3 + 7L + 4 = 7 + 7L$. Since $L \le 8$ for an $8$-bit number, no input takes more than $63$ steps.

**Exercise 13.13 ★★★.**

Write `divide.toy`, which reads $a$ and $b > 0$ and prints the quotient and the remainder of $a$ by $b$, by repeated subtraction.

**Solution of Exercise 13.13.**

While $a \ge b$ (`CMP R0, R1` then `JC done`), subtract $b$ from $a$ and add $1$ to the quotient; then print the quotient and what is left of $a$, the remainder (`exercises/divide.toy`; the tests compare it with `//` and `%` on $888$ pairs).

**Exercise 13.14 ★★★.**

A program needs $d$ cells of data, and calls [subroutines](#def-g11-von-neumann-machine-subroutine) nested at most $k$ deep, each of which pushes at most $p$ registers. How many instructions can its code have at most, so that the stack never reaches the code or the data? Apply it to $d = 30$, $k = 4$, $p = 2$.

**Solution of Exercise 13.14.**

$i$ instructions take $2i$ cells from address $0$, then come the $d$ data cells. Each level of call pushes a return address and at most $p$ registers: the stack holds at most $k(1 + p)$ cells, from $255$ down. Nothing overlaps if $2i + d + k(1 + p) \le 256$. For $d = 30$, $k = 4$, $p = 2$: $2i \le 256 - 30 - 12 = 214$, so at most $107$ instructions.

**Exercise 13.15 ★★★.**

Translate into toy assembly, and test on several inputs:

    `while a != b:` `if a > b: a = a - b` `else: b = b - a`

which leaves in `a` the greatest common divisor of two numbers $a, b \ge 1$; the program reads $a$ and $b$ and prints the result.

**Solution of Exercise 13.15.**

After reading $a$ into `R0` and $b$ into `R1`: `CMP R0, R1`; `JZ done` when they are equal; `JC` to a block that does `SUB R1, R0` when $a < b$; otherwise `SUB R0, R1`; both [jump](#def-g11-von-neumann-machine-jump) back to the comparison; `done` prints `R0` (`exercises/gcd.toy`). The tests compare it with `math.gcd` on $720$ pairs.

## 13.7 Problem: Multiplication on a Machine That Cannot

**Problem 13.1.**

Weekend problem — two ways to multiply, and their cost

The toy machine has no instruction to multiply. The program `multiply.toy` adds $a$ to a total $b$ times. The program below uses the binary digits of $b$ instead: $a \times b$ is the sum of $a \times 2^i$ over the bits $i$ of $b$ that are $1$, and $a \times 2^i$ is $a$ shifted left $i$ times.

```text
; shift_multiply.toy -- a * b by shifts and additions, one bit of b at a time
        IN    R0            ; a, doubled at each bit
        IN    R1            ; b, halved at each bit
        LOADI R2, 0         ; the product
loop:   ADDI  R1, 0         ; Z when no bit of b is left
        JZ    done
        SHR   R1            ; the lowest bit of b goes into C
        JC    add
        JMP   next
add:    ADD   R2, R0        ; this bit is 1: add a times its weight
next:   SHL   R0
        JMP   loop
done:   OUT   R2
        HALT
```

***Listing 13.9.** Multiplication by shifts and additions. code/grade-11/02-von-neumann-machine/listings/shift_multiply.toy*

```python
"""Problem: the steps of both multiplications, for every b from 0 to 255."""
from pathlib import Path

from toymachine import Machine, assemble

HERE = Path(__file__).parent


def steps(program, a, b):
    m = Machine(program, inputs=[a, b])
    m.run()
    assert m.outputs == [a * b % 256]
    return m.steps


repeated = assemble((HERE / "multiply.toy").read_text())
shifting = assemble((HERE / "shift_multiply.toy").read_text())
for name, program in (("repeated addition", repeated), ("shift and add", shifting)):
    counts = [steps(program, 13, b) for b in range(256)]
    worst = max(counts)
    mean = sum(counts) / 256
    print(f"{name:17}: b = 0 -> {counts[0]:3} steps, b = 1 -> {counts[1]:3},"
          f" worst {worst} (first at b = {counts.index(worst)}), mean {mean:.1f}")
```

***Listing 13.10.** Both programs run for every $b$ from $0$ to $255$, with $a = 13$. code/grade-11/02-von-neumann-machine/listings/step_counts.py*

```
$ python step_counts.py
repeated addition: b = 0 ->   8 steps, b = 1 ->  11, worst 773 (first at b = 255), mean 390.5
shift and add    : b = 0 ->   7 steps, b = 1 ->  14, worst 63 (first at b = 128), mean 56.0
```

***Output 13.10.** The steps of both methods. Every product is checked against Python’s, modulo $256$.*

**Part I — Repeated addition.**

1. Count the steps of `multiply.toy` for $b = 0$ , line by line.
2. Show that for $b \ge 1$ it takes $8 + 3b$ steps. Check $b = 1$ and $b = 255$ against the output.
3. Does the number of steps depend on $a$ ?
4. Compute the mean over the $256$ values of $b$ , and compare with the output.

**Part II — Shift and add.**

5. Run `shift_multiply.toy` by hand for $a = 13$ , $b = 11$ : give `R0` , `R1` , `R2` at each passage through `loop` .
6. Why does `SHR R1` followed by `JC` test the lowest bit of $b$ ?
7. What does `SHL R0` compute, and why must it run at every turn, whether the bit was $1$ or $0$ ?
8. Show that the loop turns once per bit of $b$ , up to its highest $1$ .
9. What happens to the product when it does not fit in $8$ bits?

**Part III — Counting all the cases.**

10. Count the steps of one turn of the loop when the bit is $1$ , and when it is $0$ .
11. Deduce that the program takes $7 + 7L$ steps, where $L$ is the number of bits of $b$ . Check $b = 0$ and $b = 1$ .
12. For how many values of $b$ is $L = 8$ ? Explain why the worst case is first reached at $b = 128$ .
13. Compute the mean number of steps from the number of values of $b$ having each $L$ , and compare with $56.0$ .
14. In `step_counts.py` , what does the `assert` in `steps` check, and why is `% 256` needed?

**Part IV — The worst cases.**

15. Give the worst case of each method, and their ratio.
16. For which values of $b$ is repeated addition faster? Faster by how much at most?
17. A program combines both: repeated addition for small $b$ , shift and add otherwise. Where should it switch?
18. On a machine with $16$ -bit registers, what would the worst cases become?
19. Real processors have a multiplication instruction, built as a circuit. Which idea of this problem does such a circuit use, and what does it do at once that the program does one turn at a time?
20. State the result: the worst-case steps of both methods over all $8$ -bit values of $b$ , and the formula for shift and add.

**Solution of Problem 13.1.**

**1.** `IN`, `IN`, `LOADI`, `LOADI`, `ADDI`, `JZ` (taken), `OUT`, `HALT`: $8$ steps.

**2.** The same $6$ steps before the loop, $3$ per turn for $b$ turns, then `OUT` and `HALT`: $8 + 3b$. For $b = 1$, $11$; for $b = 255$, $773$, as printed.

**3.** No: `R0` is only added, never tested.

**4.** $\frac{1}{256}\left(8 + \sum_{b=1}^{255} (8 + 3b)\right) = 8 + \frac{3}{256} \cdot \frac{255 \times 256}{2}
= 8 + 382.5 = 390.5$, as printed.

**5.** At `loop`: $(13, 11, 0)$, then $(26, 5, 13)$, $(52, 2, 39)$, $(104, 1, 39)$, $(208, 0, 143)$; the last test finds $b = 0$, and the program prints $143$.

**6.** `SHR` moves every bit one place right, and the bit that falls out, the lowest, goes into $C$; `JC` [jumps](#def-g11-von-neumann-machine-jump) exactly when it was $1$.

**7.** $2a$: after $i$ turns `R0` holds $a \times 2^i$, the value of bit $i$ of $b$. It must double at every turn so that it matches the weight of the next bit, which the next turn tests, whatever this one was.

**8.** Each turn halves `R1`, dropping its lowest bit; it becomes $0$ once every bit up to the highest $1$ has been dropped, after $L$ turns.

**9.** `ADD` and `SHL` wrap modulo $256$, so the program prints $a \times b \bmod 256$, the low byte of the product.

**10.** $7$ in both cases (the list is in the solution of exercise 12): taking `JC` to `add` costs the `ADD`, not taking it costs a `JMP next`.

**11.** $3$ steps before, $7$ per turn, $4$ at the end: $7 + 7L$. For $b = 0$, $L = 0$ and $7$ steps; for $b = 1$, $L = 1$ and $14$; as printed.

**12.** $L = 8$ for $b$ from $128$ to $255$: $128$ values. $128 = 10000000$ is the smallest of them, so the worst case, $7 + 56 = 63$, appears first there.

**13.** One value has $L = 0$, and $2^{L - 1}$ values have each $L$ from $1$ to $8$. The mean is

$$
\frac{1}{256}\left(7 + \sum_{L=1}^{8} 2^{L-1}(7 + 7L)\right) = \frac{7 + 1785 + 12\,551}{256} =
\frac{14\,343}{256} \approx 56.03,
$$

printed $56.0$.

**14.** That the machine printed exactly one number, the product modulo $256$: the machine’s arithmetic wraps while Python’s does not.

**15.** $773$ and $63$ steps: repeated addition is about $12.3$ times slower in the worst case.

**16.** For $b$ from $1$ to $6$, and $8$; at $b = 9$ both take $35$. The largest saving is $8$ steps, at $b = 4$ ($20$ against $28$).

**17.** Below $7$, but the test that chooses costs a `CMP` and a [jump](#def-g11-von-neumann-machine-jump), $2$ steps, which eats most of a saving of at most $8$: it is not worth it.

**18.** Repeated addition: $8 + 3 \times 65\,535 = 196\,613$ steps; shift and add: $7 + 7 \times 16 = 119$.

**19.** The same idea, shifted copies of $a$ for the bits of $b$ that are $1$, added up. The circuit makes all the shifted copies at once with AND gates and adds them with a tree of adders, in a few levels of gates instead of one turn per bit.

**20.** Over all $8$-bit values of $b$, multiplication by repeated addition takes up to $773$ steps ($8 + 3b$), and by shift and add at most $63$ ($7 + 7L$, where $L \le 8$ is the number of bits of $b$): about $12$ times fewer in the worst case, and $56.0$ against $390.5$ steps on average.
