Sikau

How computers work · Day 10 · about 40 min

Fetch, decode, execute

Programs live in memory; a program counter and a loop bring them to life.

Meet your CPU

A CPU does one thing, forever: fetch the instruction at the program counter (PC), decode what it means, execute it, move on. Registers hold the numbers it's working with; jumps change the PC so programs can loop and decide. Press Step and watch.

The instruction cycle in code

Our machine's instruction set: LOAD r n puts a number in a register, ADD r s/SUB r s do arithmetic (8 bits, wrapping), JMP n jumps, JZ r n jumps only if the register is zero, OUT r prints, HALT stops.

function step(state, program) {
  if (state.halted) return state;
  const [op, x, y] = program[state.pc].trim().split(/\s+/);
  const regs = { ...state.regs };
  let pc = state.pc + 1;
  let out = state.out;
  let halted = false;
  switch (op) {
    case "LOAD": regs[x] = Number(y) & 255; break;
    case "ADD": regs[x] = (regs[x] + regs[y]) & 255; break;
    case "SUB": regs[x] = (regs[x] - regs[y] + 256) & 255; break;
    case "JMP": pc = Number(x); break;
    case "JZ": if (regs[x] === 0) pc = Number(y); break;
    case "OUT": out = [...out, regs[x]]; break;
    case "HALT": halted = true; pc = state.pc; break;
    default: throw new Error(`Unknown instruction: ${op}`);
  }
  return { pc, regs, out, halted };
}

The rest of this lesson

  • The program counter drives everythingexplain
  • Immutable stepsexplain
  • What's printed?predict
  • One tick of the CPUorder
  • Write the step functionwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of How computers work