Fetch, Decode, Execute: How an Emulator's CPU Loop Works
Learn the three-step loop at the heart of every emulator: fetch an opcode, decode its fields, execute its effect, with a complete C example you can follow.

Every processor ever built does the same three things forever. It fetches an instruction from memory, decodes what the instruction means and executes it, then moves on to the next one. An emulator is a program that does those three things in software for a processor that may not exist anymore. Once you can see the loop clearly, the rest of emulator writing is filling in details: which instructions exist, which registers they touch and what flags they change. This post builds the loop from a blank file for a very small instruction set, explains each of the three steps with real code and shows the mistakes beginners make. It uses plain C11, and the instruction format comes from CHIP-8, an old and friendly virtual machine, because its instructions are two bytes long and easy to read. You need to know what a variable, an array and a switch statement are, and nothing about processors.
What the processor keeps in its head
Before the loop makes sense, you need to know what it operates on. A processor has a few tiny storage slots called registers, and it can read and write a large array of bytes called memory. Two registers matter most for the loop:
The program counter (PC) holds the memory address of the next instruction to run.
The instruction register is where the fetched instruction waits while it is decoded. In an emulator this is usually just a local variable.
The machine in this post has 4096 bytes of memory, sixteen 8-bit general registers named V0 to VF, and a program counter. Programs are loaded at address 0x200, which is where CHIP-8 programs have always started. Every instruction is exactly two bytes.
#include <stdint.h>
typedef struct {
uint8_t memory[4096];
uint8_t v[16]; /* general registers V0..VF */
uint16_t pc; /* program counter */
} Machine;The register array uses uint8_t so values wrap at 255, as an 8-bit register on the real machine would. The program counter is uint16_t because addresses go up to 4095, which needs more than eight bits.
Step one: fetch
Fetching means reading the instruction at the address in the program counter and then moving the counter past it. Because each instruction is two bytes, the fetch reads two bytes and combines them into one 16-bit number. The order matters: this machine stores the high byte first, which is called big-endian.
#include "machine.h"
uint16_t fetch(Machine *m)
{
uint16_t hi = m->memory[m->pc];
uint16_t lo = m->memory[m->pc + 1];
m->pc += 2;
return (uint16_t)((hi << 8) | lo);
}If memory at 0x200 holds the bytes A2 F0, the fetch returns 0xA2F0 and leaves the program counter at 0x202. Shifting the high byte left by eight places puts it in the upper half of the result, and the bitwise OR fills in the lower half.
Advancing the counter inside the fetch, before the instruction runs, is the usual choice, and it has a consequence worth remembering: while an instruction executes, the program counter already points at the next instruction. A jump simply overwrites the counter. A skip, which means "do not run the next instruction", adds two more.
Step two: decode
The 16-bit number is a packed set of fields. Decoding means pulling the fields apart with shifts and masks so that the execute step can use them. On this machine the top four bits, the high nibble, say which family the instruction belongs to, and the rest depend on the family.
| Name | Bits | How to extract it | Typical use |
|---|---|---|---|
op | 15 to 12 | (instr >> 12) & 0xF | Which family of instruction |
x | 11 to 8 | (instr >> 8) & 0xF | A register index |
y | 7 to 4 | (instr >> 4) & 0xF | A second register index |
n | 3 to 0 | instr & 0xF | A 4-bit number |
nn | 7 to 0 | instr & 0xFF | An 8-bit number |
nnn | 11 to 0 | instr & 0xFFF | A 12-bit address |
A decoder extracts every field up front, and each instruction then uses whichever ones it needs. That wastes a few shifts on each instruction, which does not matter, and it keeps the execute code short and readable.
#include <stdint.h>
typedef struct {
uint8_t op;
uint8_t x, y, n;
uint8_t nn;
uint16_t nnn;
} Decoded;
Decoded decode(uint16_t instr)
{
Decoded d;
d.op = (instr >> 12) & 0xF;
d.x = (instr >> 8) & 0xF;
d.y = (instr >> 4) & 0xF;
d.n = instr & 0xF;
d.nn = instr & 0xFF;
d.nnn = instr & 0xFFF;
return d;
}For 0xA2F0, the decoded fields are op = 0xA, x = 2, y = 0xF, n = 0, nn = 0xF0 and nnn = 0x2F0. The same bits are interpreted as an address or as two register numbers depending on which family op selects, which is why decoding is only half the job: the opcode tells you how to read the other fields.
Step three: execute
Execution is a switch on the family, with a case for each instruction. Take five instructions that are enough to write a real program.
6XNNsets registerVXto the valueNN.7XNNaddsNNtoVX, wrapping at 256, and does not touch the carry register.1NNNjumps: it sets the program counter toNNN.3XNNskips the next instruction ifVXequalsNN.00E0and the others in family 0 are system instructions; here we treat anything unknown as a stop signal.
#include <stdbool.h>
#include "machine.h"
typedef struct {
uint8_t op, x, y, n, nn;
uint16_t nnn;
} Decoded;
bool execute(Machine *m, Decoded d)
{
switch (d.op) {
case 0x1: /* 1NNN: jump */
m->pc = d.nnn;
return true;
case 0x3: /* 3XNN: skip if VX == NN */
if (m->v[d.x] == d.nn)
m->pc += 2;
return true;
case 0x6: /* 6XNN: VX = NN */
m->v[d.x] = d.nn;
return true;
case 0x7: /* 7XNN: VX += NN, no carry flag */
m->v[d.x] = (uint8_t)(m->v[d.x] + d.nn);
return true;
default:
return false; /* unknown instruction: stop */
}
}The return false default gives the loop a way to stop when it meets an instruction it does not know, which is far more useful than silently ignoring it. A lot of emulator time goes into finding out which instruction you have not written yet, and an immediate, loud stop that prints the opcode and the program counter turns that into a thirty-second task.
The loop
Joining the three steps is a single while loop.
#include <stdio.h>
#include <string.h>
#include "machine.h"
uint16_t fetch(Machine *m);
Decoded decode(uint16_t instr);
bool execute(Machine *m, Decoded d);
int main(void)
{
static Machine m;
memset(&m, 0, sizeof m);
m.pc = 0x200;
/* 6005: V0 = 5
7003: V0 += 3
3008: skip next if V0 == 8
1200: jump to 0x200 (skipped)
FFFF: unknown, stops the loop */
const uint8_t program[] = {
0x60, 0x05, 0x70, 0x03, 0x30, 0x08, 0x12, 0x00, 0xFF, 0xFF,
};
memcpy(&m.memory[0x200], program, sizeof program);
for (;;) {
uint16_t pc_before = m.pc;
uint16_t instr = fetch(&m);
Decoded d = decode(instr);
if (!execute(&m, d)) {
printf("stopped at 0x%03X on instruction 0x%04X\n", pc_before, instr);
break;
}
}
printf("V0 = %u\n", m.v[0]);
return 0;
}Walk through it by hand. 6005 sets V0 to 5. 7003 adds 3, so V0 is 8. 3008 compares V0 with 8, finds them equal and skips the next instruction, which is the jump back to the start. Control then reaches FFFF, which the machine does not know, and the loop stops.
stopped at 0x208 on instruction 0xFFFF
V0 = 8Without the skip, the jump to 0x200 would send the program back to the start, and it would run forever. That is the whole of control flow: jumps and conditional skips edit the program counter, and everything else just moves data between registers and memory.
Why order and timing matter in the loop
Three details of the loop cause most of the first-day bugs.
Fetch before execute, always. If you advance the counter after execution instead of during the fetch, a jump to address X sets the counter to X and then adds two, so the first instruction at X is skipped.
Read the instruction's operands from a stable copy. The decoded fields are copied out of the instruction before execution, so changing a register in the middle of an instruction cannot change the register number the instruction meant. That is automatic here because Decoded is a separate value, and it becomes important for instructions that read and write the same register.
Handle the unknown instruction on purpose. Stopping with a message, as above, finds missing instructions quickly. The alternative of skipping unknown instructions hides them until the program misbehaves forty frames later.
Counting cycles
The loop above runs as fast as the host allows. To run at the speed of the original, you count how many instructions to run between screen updates. CHIP-8 has no fixed official speed, and emulators typically run about 500 to 1000 instructions per second, with a timer that ticks at 60 Hz. The simplest scheme runs a fixed number of instructions per frame:
#define INSTRUCTIONS_PER_FRAME 10
void run_frame(Machine *m)
{
for (int i = 0; i < INSTRUCTIONS_PER_FRAME; i++) {
uint16_t instr = fetch(m);
if (!execute(m, decode(instr)))
return;
}
}At 60 frames per second and 10 instructions per frame, that runs 600 instructions per second. The right figure depends on the program, so make it adjustable. More accurate emulators of other machines count cycles per instruction, which is a separate topic.
What changes for a real processor
The structure of the loop does not change for bigger machines. Variable-length instructions mean the fetch reads one byte, decodes it and then fetches operand bytes as needed. A processor with many addressing modes needs a decoder that returns an operand location in addition to an operation. Interrupts add a check between instructions. Cycle-exact machines run their video chip a few cycles at a time between instructions. But the three-step shape remains, and a reader who has understood it here will recognize it in the 6502 and RISC-V emulators in this cluster.


