Skip to content

Instantly share code, notes, and snippets.

@dyama
Last active August 29, 2015 14:18
Show Gist options
  • Save dyama/7a466dce22b1d6ffcc46 to your computer and use it in GitHub Desktop.
Save dyama/7a466dce22b1d6ffcc46 to your computer and use it in GitHub Desktop.
Brain F*ck Interpretor
#include <stdio.h>
#define RAMSIZE 30000
int main(int argc, char **argv)
{
FILE *f; /* インストラクションポインタ */
int *p; /* データポインタ */
int b[RAMSIZE] = { 0 }; /* バッファ */
char c; /* 文字 */
int i; /* カウンタ */
p = b;
if ((f = fopen(argv[1], "r")) == NULL) {
f = stdin;
}
while ((c = (char)fgetc(f)) != EOF) {
switch (c) {
case '>':
p++;
break;
case '<':
p--;
break;
case '+':
(*p)++;
break;
case '-':
(*p)--;
break;
case '.':
fputc(*p, stdout);
break;
case ',':
*p = fgetc(stdin);
break;
case '[':
if (*p == 0) {
for (i = 0; c != ']' || i;) {
if ((c = (char)fgetc(f)) == EOF) {
return 1;
}
if (c == '[') {
i++;
}
else if (c == ']' && i) {
i--;
}
}
}
break;
case ']':
if (*p != 0) {
for (i = 0; c != '[' || i;) {
if (fseek(f, -2, SEEK_CUR)) {
return 1;
}
if ((c = (char)fgetc(f)) == EOF) {
return 1;
}
if (c == ']') {
i++;
}
else if (c == '[' && i) {
i--;
}
}
}
break;
}
}
return 0;
}
+++++++++[>++++++++>+++++++++++>+++++<<.>++.+++++++..+++.>-.------------.+.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment