Last active
August 29, 2015 14:20
-
-
Save mrnugget/81f91e41c736f47a743e to your computer and use it in GitHub Desktop.
Simple brainfuck interpreter in C
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
| #include <string.h> | |
| #include <stdio.h> | |
| #define MEM_SIZE 30000 | |
| char mem[MEM_SIZE] = {0}; | |
| char *memp = mem; | |
| void bf_eval(char *code, int len, FILE *in, FILE *out) | |
| { | |
| int ip = 0; | |
| while (ip < len) { | |
| switch (code[ip]) { | |
| case '+': | |
| ++*memp; | |
| break; | |
| case '-': | |
| --*memp; | |
| break; | |
| case '>': | |
| memp++; | |
| break; | |
| case '<': | |
| memp--; | |
| break; | |
| case '.': | |
| putc(*(int *)memp, out); | |
| break; | |
| case ',': | |
| *memp = getc(in); | |
| break; | |
| case '[': | |
| if (*memp == 0) { | |
| int depth = 1; | |
| while (depth != 0) { | |
| ip++; | |
| if (code[ip] == '[') { | |
| depth++; | |
| } else if (code[ip] == ']') { | |
| depth--; | |
| } | |
| } | |
| } | |
| break; | |
| case ']': | |
| if (*memp != 0) { | |
| int depth = 1; | |
| while (depth != 0) { | |
| ip--; | |
| if (code[ip] == ']') { | |
| depth++; | |
| } else if (code[ip] == '[') { | |
| depth--; | |
| } | |
| } | |
| } | |
| break; | |
| } | |
| ip++; | |
| } | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| char *test_code = "+++>++>++>++>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.."; | |
| bf_eval(test_code, strlen(test_code), stdin, stdout); | |
| printf("\n----------\n"); | |
| printf("mem[0]: %d\n", mem[0]); | |
| printf("mem[1]: %d\n", mem[1]); | |
| printf("mem[2]: %d\n", mem[2]); | |
| printf("mem[3]: %d\n", mem[3]); | |
| printf("\n----------\n"); | |
| // reset memory pointer and memory | |
| memp = mem; | |
| memset(mem, 0, MEM_SIZE); | |
| char *hello_world = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; | |
| bf_eval(hello_world, strlen(hello_world), stdin, stdout); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment