Last active
September 1, 2022 14:45
-
-
Save kodejuice/77eee56c2ea5f983d4be3e2480d695eb to your computer and use it in GitHub Desktop.
A simple 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
char * brain_fuck(char * code, char * input){ | |
const int BUFSIZE = 30000; | |
int * ptr = (int *) malloc(BUFSIZE * sizeof(int)), | |
i_sz = strlen(input), c_sz = strlen(code), | |
idx = -1, j = 0, o = 0; | |
char cmd, * output = (char *) malloc(BUFSIZE); | |
while (idx++ < c_sz){ | |
cmd = code[idx]; | |
if (cmd == '.' && *ptr > 0 && *ptr < 256) output[o++] = (char) *ptr; | |
else if (cmd == '+') *ptr = ((*ptr | 0) + 1) % 256; | |
else if (cmd == '-') *ptr = ((*ptr | 0) - 1), *ptr = *ptr == -1 ? 255 : *ptr; | |
else if (cmd == '>') ptr++; | |
else if (cmd == '<') ptr--; | |
else if (cmd == ',' && j < i_sz) *ptr = input[j++]; | |
else if (cmd == '['){ | |
int open = 1, i = idx + 1; | |
*ptr = (*ptr | 0); | |
if (!*ptr){ | |
while (open && i++ < c_sz) | |
if (code[i-1] == '[') open += 1; | |
else if(code[i-1] == ']') open -= 1; | |
idx = i - 1; | |
} | |
} | |
else if (cmd == ']'){ | |
int open = 1, i = idx - 1; | |
*ptr = (*ptr | 0); | |
if (*ptr){ | |
while (open && i-- >= 0) | |
if (code[i+1] == '[') open -= 1; | |
else if (code[i+1] == ']') open += 1; | |
idx = i + 1; | |
} | |
} | |
} | |
output[o] = '\0'; | |
return output; | |
} | |
brain_fuck(",[.>,]", "hello"); //=> "hello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this looks buggy, lol