Created
February 22, 2013 11:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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