A CHIP-8 interpreter needs somewhere to keep both bytecode and the state used to execute it. Its addressable memory is 4,096 bytes; instructions occupy two bytes each, combining an opcode with any operands. section 6.2.1 section 6.3.2
A practical Zig representation groups memory and CPU registers in one Memory struct. The data array holds 0x1000 bytes; pc and i are 12-bit registers, and vars holds sixteen 8-bit registers. The I register stores pointers, while pc tracks the program counter. 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,
}
Inspect the fixed-size byte array and register fields in the Memory struct. section 6.3.2
To run a program, create a Memory value, load bytecode with loadProgram, and pass it to the interpreter’s step function. In a frame loop, step after reading the keypad and before drawing the display so input and output stay responsive. section 6.4.4
Addresses 0 through 0x1FF are reserved for the interpreter. One stack implementation starts at address zero: pushing stores the 12-bit program counter in two bytes and advances a stack pointer by two; popping reverses those operations. The stack pointer can be a Memory field or live in reserved memory, but loadProgram must reset it to its base value. section 6.5.6
Loading and stepping bytecode
A runtime can load an original CHIP-8 .bin program and call step 1,000 times per frame. The program may run before every instruction is implemented, although it can still encounter an unimplemented instruction. section 6.4.4
