Decode instructions

Decode 16-bit instructions in this format: bits 15–12 are the opcode, bits 11–8 rd, bits 7–4 rs and bits 3–0 rt (or a constant c from 0 to 15).

OpcodePrint
0NOP
1, 2, 3, 4ADD, SUB, AND, OR as ADD rd, rs, rt, e.g. ADD r1, r2, r3
5ADDI rd, rs, c, e.g. ADDI r2, r1, 5
6LW rd, c(rs), e.g. LW r3, 4(r0)
7SW rd, c(rs)
8 to 15UNKNOWN

Input

A line with n (1 ≤ n ≤ 100), then n instructions, each as 4 hex digits.

Output

One decoded instruction per line.

Examples

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

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

Hints

Hint 1

Read each word with int(word, 16).

Hint 2

opcode = (w >> 12) & 0xF, rd = (w >> 8) & 0xF, rs = (w >> 4) & 0xF, rt = w & 0xF.

Hint 3

Match the opcode to its format: three registers, a register and a constant, or a memory operand c(rs).

Solution

Show one correct solution (try it yourself first)
NAMES = {1: "ADD", 2: "SUB", 3: "AND", 4: "OR"}
n = int(input())
for _ in range(n):
    w = int(input().strip(), 16)
    op, rd, rs, rt = (w >> 12) & 0xF, (w >> 8) & 0xF, (w >> 4) & 0xF, w & 0xF
    if op == 0:
        print("NOP")
    elif op in NAMES:
        print(f"{NAMES[op]} r{rd}, r{rs}, r{rt}")
    elif op == 5:
        print(f"ADDI r{rd}, r{rs}, {rt}")
    elif op == 6:
        print(f"LW r{rd}, {rt}(r{rs})")
    elif op == 7:
        print(f"SW r{rd}, {rt}(r{rs})")
    else:
        print("UNKNOWN")

Lesson: Instruction sets and addressing modes →