Skip to content
systemcoding.dev
Virtualization

Decode SM83 opcodes with x, y and z bit fields

Split every Game Boy SM83 opcode into x, y and z bit fields to decode the whole 8-bit load block with one table instead of 64 switch cases.

1 min read
Summarize in AI

A Game Boy emulator that writes one case per opcode ends up with 256 near-identical arms. The SM83 encoding is regular enough to avoid that: cut the opcode into x (bits 7-6), y (bits 5-3) and z (bits 2-0), and most of the instruction set falls out of those three numbers.

decode.cc
static const char *R[8] = { "B", "C", "D", "E", "H", "L", "(HL)", "A" };

void decode(unsigned char op) {
    unsigned x = op >> 6, y = (op >> 3) & 7, z = op & 7;
    if (x == 1) {
        if (op == 0x76) puts("HALT");
        else printf("LD %s,%s\n", R[y], R[z]);
    }
}

Feeding it 0x41, 0x7E and 0x76:

Text
LD B,C
LD A,(HL)
HALT

For x == 1 the opcode is LD r,r', with y as the destination and z as the source, both indexing the register order B, C, D, E, H, L, (HL), A. The one hole is 0x76, which would be LD (HL),(HL) and is HALT instead, so test it before the table. The x == 2 block (ADD, ADC, SUB and friends) reuses the same z register table with y picking the ALU operation. The layout is described in the Pan Docs instruction set reference. The pattern stops helping in x == 0 and x == 3, which mix unrelated instructions, so handle those with ordinary cases.

Also inHardware
Taggedc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.