Skip to content

Instantly share code, notes, and snippets.

@timosarkar
Last active October 20, 2025 19:38
Show Gist options
  • Select an option

  • Save timosarkar/e74b30c198400599381c731656261362 to your computer and use it in GitHub Desktop.

Select an option

Save timosarkar/e74b30c198400599381c731656261362 to your computer and use it in GitHub Desktop.
simple register vm with a tiny assembly language and VRAM
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NUM_REGS 4
#define MAX_LINE 100
#define WIDTH 10
#define HEIGHT 10
int registers[NUM_REGS];
int vram[HEIGHT][WIDTH];
int reg_index(char *r) {
if (r[0] == 'R') return r[1] - '0';
return -1;
}
void draw() {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
printf(vram[y][x] ? "#" : " ");
}
printf("\n");
}
}
void execute(char *line) {
char *tokens[4];
int token_count = 0;
char *token = strtok(line, " ,\n");
while (token && token_count < 4) {
tokens[token_count++] = token;
token = strtok(NULL, " ,\n");
}
if (token_count == 0) return; // empty line
if (strcmp(tokens[0], "MOV") == 0) {
int r = reg_index(tokens[1]);
int val = atoi(tokens[2]);
registers[r] = val;
} else if (strcmp(tokens[0], "ADD") == 0) {
int dest = reg_index(tokens[1]);
int src1 = reg_index(tokens[2]);
int src2 = reg_index(tokens[3]);
registers[dest] = registers[src1] + registers[src2];
} else if (strcmp(tokens[0], "SETPIX") == 0) {
int x = atoi(tokens[1]);
int y = atoi(tokens[2]);
int val = atoi(tokens[3]);
if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT) {
vram[y][x] = val;
}
} else if (strcmp(tokens[0], "DRAW") == 0) {
draw();
} else if (strcmp(tokens[0], "PRINT") == 0) {
int r = reg_index(tokens[1]);
printf("%d\n", registers[r]);
} else if (strcmp(tokens[0], "EXIT") == 0) {
exit(0);
} else {
printf("Unknown instruction: %s\n", tokens[0]);
}
}
int main() {
char line[MAX_LINE];
printf("Register VM REPL with VRAM (10x10)\nType EXIT to quit\n");
while (1) {
printf(">> ");
if (!fgets(line, sizeof(line), stdin)) break;
execute(line);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment