Skip to content

Instantly share code, notes, and snippets.

@kodejuice
Last active September 1, 2022 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kodejuice/77eee56c2ea5f983d4be3e2480d695eb to your computer and use it in GitHub Desktop.
Save kodejuice/77eee56c2ea5f983d4be3e2480d695eb to your computer and use it in GitHub Desktop.
A simple brainfuck interpreter written in C
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"
@kodejuice
Copy link
Author

this looks buggy, lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment