Lesson 5 of 8
The disassembler
- 16 min
- 5 checks
- 3 hints
- Go to task
Goal
From numbers to readable names
Explanation
The list of tuples is precise, but it's all numbers. A disassembler turns it into names a person can read, so instead of (1, 72) you see LOAD 0x48. That's exactly what the big analysis tools do with real CPU instructions, except their table has hundreds of instructions.
Here are the machine's instructions again:
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)
You'll need a dictionary that maps each opcode to its name:
NAMES = {
0x00: "HALT", 0x01: "LOAD",
0x02: "ADD", 0x03: "XOR",
0x04: "SUB", 0x05: "OUT",
}
The line format is fixed: the instruction's name, then a space and the operand in hex if it has one. The hex function writes a number with the 0x prefix and no leading zeros, so hex(1) returns "0x1" and hex(72) returns "0x48".
The decode function from the previous lesson is already in the starter code, so build on it.
Your task
Write the function disasm(program) that returns a list of strings, one line per instruction, such as "LOAD 0x48" for an instruction with an operand and "OUT" for one without.
Checks
5 checks- The first line has LOAD and its operand
- An instruction without an operand is just its name
- The operand is written with hex, without a leading zero
- The full list of five lines
- Works on another program you haven't seen