We read and wrote the multiplication and
odd-or-even programs with mnemonics,
like LOAD 14. But the CPU only reads binary like 01100011, which is
machine code, so memory has to hold binary. Does a person
have to translate it one bit at a time?
A language that writes machine instructions one per line with mnemonics, like
LDI R0, 3, is called assembly language. Each line of assembly turns into
exactly one machine instruction, so translating it only takes looking things up
in the table from the instruction set post. A program
that does this for us is an assembler.
| Address | Assembly | Machine code |
|---|---|---|
| 0 | LDI R0, 3 | 0110 0011 |
| 1 | ADD R2, R0 | 0001 1000 |
| 2 | SUBI R1, 1 | 0101 0101 |
| 3 | HALT | 1111 0000 |
The odd-or-even program checks whether the number at address 13 is odd and writes the result to address 15. What happens if we give the odd-or-even program below more work by adding instructions at the top?
Switch between the original and the one with six lines added at the top.
Adding lines pushed every instruction after them down six slots, but addresses
like the ones in JZ 6 and JUMP 1 stayed the same, so they jump to the wrong
lines. STORE 15 now sits at address 13, taking the place of the number to
test. Every time we add lines, we have to find and fix every one of these
addresses.
So in assembly, we put a name called a label in front of a line and use that
name instead of the address. Data gets a name too, written at the end of the
program like num: DATA 7. That means “put the value 7 here instead of an
instruction, and call this slot num.”
Labels loop = 1, odd = 6, even = 7, num = 9, out = 10
| Address | Assembly | Machine code |
|---|---|---|
| 0 | LOAD num | 1000 1001 |
| 1 | SUBI R0, 1 | 0101 0001 |
| 2 | JZ odd | 1101 0110 |
| 3 | SUBI R0, 1 | 0101 0001 |
| 4 | JZ even | 1101 0111 |
| 5 | JUMP loop | 1100 0001 |
| 6 | LDI R0, 1 | 0110 0001 |
| 7 | STORE out | 1001 1010 |
| 8 | HALT | 1111 0000 |
| 9 | DATA 7 | 0000 0111 |
| 10 | DATA 0 | 0000 0000 |
Add any instruction at the top. The labels’ addresses shift on their own, and the machine code follows.
The assembler reads the program twice. The first time it counts the address of every label, and the second time it replaces names with addresses and produces machine code. Data always sits after the program, so it never collides with instructions. A data slot with a name like this is called a variable.
The computer so far handles one instruction from start to finish in a single clock, so the clock can’t be any faster than that. In the next post, let’s look at how to process instructions faster with the same parts.
When the assembler translates the program below, what is the machine code for the JZ end line? JZ's opcode is 1101, and the last 4 bits are the address to jump to. Answer with 8 digits, no spaces.
LDI R1, 3
loop: SUBI R1, 1
JZ end
JUMP loop
end: HALT