Lesson 4 of 8
A tiny machine: decoding
- 15 min
- 6 checks
- 3 hints
- Go to task
Goal
Instructions of different lengths
Explanation
From here on you build analysis tools yourself, for a tiny machine we invented for these lessons. A virtual machine is a program that executes instructions encoded as bytes, called bytecode, just as Python itself does with your code. Understanding a small invented machine is the shortest path to understanding real ones.
Our machine has a single slot called the accumulator, which starts at zero, and six instructions. Each instruction starts with one byte, the opcode, and four of them are followed by a second byte, the operand. Each line below shows the opcode, then its name, then imm if it takes an operand, then its effect written in Python:
0x00 HALT break 0x01 LOAD imm acc = imm 0x02 ADD imm acc = (acc+imm) & 0xFF 0x03 XOR imm acc = acc ^ imm 0x04 SUB imm acc = (acc-imm) & 0xFF 0x05 OUT out.append(acc)
So the program 01 48 05 00 reads like this: LOAD with the operand 0x48, then OUT, then HALT. The byte 48 isn't an instruction but the operand of the instruction before it. That's the most important idea in decoding: instructions vary in length, so you can't know where the next instruction starts until you know the length of the current one.
That's why you walk the bytes with an index i. You read the opcode at program[i], and if it has an operand you read it from program[i + 1] and move ahead two bytes; otherwise you move ahead one byte. When you reach HALT you stop, because the bytes after it aren't instructions.
Your task
Write the function decode(program) that returns a list of tuples, one per instruction, in the form (opcode, operand), where the operand is None for an instruction that has no operand. Stop after HALT.
Checks
6 checks- The first instruction is LOAD with its operand
- OUT has no operand
- The full list of five instructions
- Stops at HALT and reads nothing after it
- Works on another program you haven't seen
- An operand is never read as an opcode, even when its value matches one