Last active
May 31, 2019 16:21
-
-
Save rw-r-r-0644/40fc3c704fab99b0f4c7595b276777ea to your computer and use it in GitHub Desktop.
Brainfuck interpreter
This file contains hidden or 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
// Brainfuck interpreter | |
#include <stdio.h> | |
#include <fcntl.h> | |
#include <stdlib.h> | |
char m[30720] = {0}, *f = NULL; | |
int p = 0; | |
void dnth() {} | |
void iptr() {p++;} | |
void dptr() {p--;} | |
void ival() {m[p]++;} | |
void dval() {m[p]--;} | |
void vout() {putchar(m[p]);} | |
void vinp() {m[p] = getchar();} | |
void jfwd() {if(!m[p])while(*(f++)!=']');} | |
void jbwd() {if(m[p]){while(*(--f)!='[');f++;}} | |
void* j[256]={[0 ... 42]=dnth,[43]=ival,[44]=vinp,[45]=dval,[46]=vout,[47 ... 59]=dnth,[60]=dptr,[61]=dnth,[62]=iptr,[63 ... 90]=dnth,[91]=jfwd,[92]=dnth,[93]=jbwd,[94 ... 255]=dnth}; | |
char* load(const char *fn) { | |
FILE *fp = fopen(fn, "rb"); | |
if (!fp) | |
exit(1); | |
fseek(fp, 0, SEEK_END); | |
int s = ftell(fp); | |
rewind(fp); | |
char* r = malloc(s + 1); | |
if (fread(r, 1, s, fp) != s) | |
exit(2); | |
fclose(fp); | |
r[s] = 0; | |
return r; | |
} | |
int main(int argc, char* argv[]) { | |
f = load(argv[1]); | |
while(*f)((void(*)())j[*(f++)])(); | |
putchar('\n'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment