Created
October 29, 2011 16:16
-
-
Save dreamersdw/1324720 to your computer and use it in GitHub Desktop.
Brainfuck interpreter written in C
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> | |
#define match(from, to, ptr, dir, level) \ | |
while(*(dir ptr)) { \ | |
if (*ptr == to && level == 0) break; \ | |
if (*ptr == from) ++level; \ | |
if (*ptr == to) --level; \ | |
} | |
char code[32768] = {0}; | |
char data[32768] = {0}; | |
void exec() { | |
char* pc = code; | |
char* p = data;; | |
int level = 0; | |
int ch; | |
while (*pc) { | |
switch(*pc) { | |
case '>': ++p; break; | |
case '<': --p; break; | |
case '+': ++*p; break; | |
case '-': --*p; break; | |
case '.': putchar(*p); break; | |
case ',': *p = ((ch = getchar()) == EOF) ? 0 : ch; break; | |
case '[': if (!*p) match('[', ']', pc, ++, level); break; | |
case ']': if ( *p) match(']', '[', pc, --, level); break; | |
default: break; | |
} | |
pc++; | |
} | |
} | |
int main(int argc, const char *argv[]) { | |
FILE* fp = fopen(argv[1], "r"); | |
char* pc = code; | |
int ch; | |
while ((ch=fgetc(fp)) != EOF) { | |
if (ch == '>' || ch == '<' || ch == '+' || ch == '-' || | |
ch == '[' || ch == ']' || ch == '.' || ch == ',') | |
*(pc++) = ch; | |
} | |
fclose(fp); | |
exec(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment