A register is a small, directly addressable storage location in a processor or virtual machine. It holds a value that instructions can read or change during computation. In a CHIP-8 interpreter, registers are part of the virtual machine’s state alongside memory, display output, and keypad input. section 6.3.2
CHIP-8 has 16 8-bit variable registers and a 12-bit pointer register called I. The interpreter also needs a 12-bit program counter to hold an address, plus 4,096 bytes of memory. In Zig, these fit neatly into a structure: an array of u8 values for the variable registers, u12 fields for I and the program counter, and a byte array for memory. section 6.2.1 section 6.3.2
Listing 6.5 Everything we can remember
pub const Memory = struct {
const Self = @This();
pub const total_memory_bytes = 0x1000; #1
pc: u12, #2
i: u12, #2
vars: [16]u8,
data: [total_memory_bytes]u8,
}
The Memory structure puts the registers and memory in one place, with their widths explicit in the Zig types. section 6.3.2
Instructions identify registers by index. In 6XKK, X selects a register and KK supplies a constant byte. Decoding that instruction can therefore use the second nibble as an array index and the second byte as the value. section 6.5.2 section 6.5.4
Listing 6.17 Value in register
0x6 => { #1
// set register to a constant
memory.vars[nibbles[1]] = bytecode[1]; #2
},
This instruction handler writes the constant byte directly into the selected register. section 6.5.4
Other instructions copy register values or perform bitwise and arithmetic operations. Width matters: an 8-bit result may overflow. Zig’s +% operator explicitly wraps addition; @addWithOverflow and @subWithOverflow return both the wrapped result and a u1 overflow indicator. Ordinary addition instead treats overflow as illegal behavior and panics in debug mode. section 6.5.4
Save registers before reusing them
A function call saves only the program counter, so a function that needs occupied registers can first save them. FX55 writes registers 0 through X, inclusive, to memory starting at I; FX65 loads them back from that address. The same pair helps when one complex operation interrupts another. section 6.5.9








