Assemble instructions

An assembler does the opposite of a disassembler: it turns readable instructions into binary. Use the same 16-bit format as in the previous exercise: bits 15–12 opcode, 11–8 rd, 7–4 rs, 3–0 rt or constant.

What to build

A program that assembles a list of instructions into 4-digit hex words.

Requirements

  • NOP becomes 0000. ADD, SUB, AND, OR take rd, rs, rt and have opcodes 1 to 4.
  • ADDI rd, rs, c has opcode 5 and puts c in the low field. LW rd, c(rs) has opcode 6 and SW rd, c(rs) opcode 7; c goes in the low field and rs in bits 7–4.
  • Mnemonics and register names may be written in any letter case. Print each word as four uppercase hex digits.

Input

A line with n, then n instructions, one per line.

Output

One word per line.

Constraints

1 ≤ n ≤ 100; registers are r0 to r15; constants are from 0 to 15.

Example

Input:

3
ADD r1, r2, r3
ADDI r2, r1, 5
LW r3, 4(r0)

Output:

1123
5215
6304

Why it works

Assembling is the decoding in reverse: place each field at its bit position with a left shift and combine them with OR. The memory forms LW and SW write the base register into the rs field and the offset into the low field.

Examples

Example 1 · Input
3
ADD r1, r2, r3
ADDI r2, r1, 5
LW r3, 4(r0)
Expected output
1123
5215
6304
Example 2 · Input
2
NOP
SW r1, 2(r4)
Expected output
0000
7142

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Use the opcode numbers NOP 0, ADD 1, SUB 2, AND 3, OR 4, ADDI 5, LW 6, SW 7.

Hint 2

Pull the numbers out of the line with re.findall(r"\d+", ...) after removing the mnemonic. For LW and SW the numbers come in the order rd, c, rs.

Hint 3

The word is (op << 12) | (rd << 8) | (rs << 4) | rt, printed with f"{w:04X}".

Solution

Show one correct solution (try it yourself first)
import re

OPS = {"NOP": 0, "ADD": 1, "SUB": 2, "AND": 3, "OR": 4, "ADDI": 5, "LW": 6, "SW": 7}
n = int(input())
for _ in range(n):
    line = input().strip().upper()
    name = line.split()[0]
    nums = [int(x) for x in re.findall(r"\d+", line[len(name):])]
    op = OPS[name]
    rd = rs = rt = 0
    if name in ("LW", "SW"):
        rd, rt, rs = nums
    elif nums:
        rd, rs, rt = nums
    w = (op << 12) | (rd << 8) | (rs << 4) | rt
    print(f"{w:04X}")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Instruction sets and addressing modes →