Exercise 48: A Tiny Virtual Machine – Part 1: Spec & Loader

Goals:

  • Understand how to design a simple CPU spec.
  • Implement a bytecode file format.
  • Load programs into memory.

Topics Covered:

  • Defining a simple instruction set: LOAD, ADD, SUB, JMP, HLT.
  • Building the memory array.
  • Writing a file format: 16-bit opcodes + operand bytes.
  • Implementing a loader in C that reads this bytecode into memory.

Code Concepts:

cCopyEdittypedef struct {
    unsigned char *code;
    int ip;  // instruction pointer
    int running;
} VM;