Decode CHIP-8 opcodes into nibbles with bit masks
Split a 16-bit CHIP-8 opcode into X, Y, N, NN and NNN with shifts and masks, after fetching it big-endian from two memory bytes.
Every CHIP-8 instruction is two bytes, stored high byte first, and the interesting parts are single hex digits. The decoder is a handful of shifts and masks, and it is the first thing a new emulator needs.
uint16_t op = (uint16_t)(mem[pc] << 8) | mem[pc + 1];
pc += 2;
unsigned group = (op & 0xF000) >> 12;
unsigned x = (op & 0x0F00) >> 8;
unsigned y = (op & 0x00F0) >> 4;
unsigned n = op & 0x000F;
unsigned nn = op & 0x00FF;
unsigned nnn = op & 0x0FFF;
printf("op %04X: group %X X=%X Y=%X N=%X NN=%02X NNN=%03X\n",
op, group, x, y, n, nn, nnn);For the opcode D125, which draws a five-row sprite, the output is:
op D125: group D X=1 Y=2 N=5 NN=25 NNN=125The top digit picks the instruction family and the other digits mean different things in each. 8XY4 uses N as part of the opcode, 6XNN uses NN as a literal, and 1NNN uses all three low digits as an address. Compute all six fields once, then let each case use the ones it needs.
The easy mistake is the fetch. CHIP-8 is big-endian, so mem[pc] | (mem[pc + 1] << 8) reads 25D1 and every opcode decodes wrongly. Advance pc by two before executing, because jumps and skips are defined relative to the next instruction, as the CHIP-8 technical reference describes.