Skip to content

Instantly share code, notes, and snippets.

@jadudm
Created February 22, 2013 11:41
Show Gist options
  • Save jadudm/5012899 to your computer and use it in GitHub Desktop.
Save jadudm/5012899 to your computer and use it in GitHub Desktop.
A demo from class; a "pico" fetch/execute virtual machine written in just over 5 minutes.
#include <stdio.h>
int code[] = {0x73, 0x75, 0x1A, 0x00};
int stack[] = {0, 0, 0};
#define A 0
#define B 1
#define C 2
void printStack () {
printf("A %02X, B %02X, C %02X\n", stack[A], stack[B], stack[C]);
}
int main () {
int pc = 0;
while (code[pc] != 0x00) {
/* Grab the nibbles. */
int upper = code[pc] >> 4;
int lower = code[pc] & 0x0F;
/* Increment the program counter. */
pc++;
switch (upper) {
/* Load a constant. */
case 7:
stack[C] = stack[B];
stack[B] = stack[A];
stack[A] = lower;
break;
/* An operation. I cheat, because
we only support ADD in this example.
*/
case 1:
stack[A] = stack[A] + stack[B];
break;
}
/* Show the stack every time we fetch and
execute an instruction.
*/
printStack();
}
/* Make C happy. */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment