Last active
July 1, 2017 01:23
-
-
Save dz1984/05e4c6cc6e72c563fd4e7af03718734f to your computer and use it in GitHub Desktop.
A simple brainfuck interpreter.
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 <stdio.h> | |
#include <stdlib.h> | |
#define MEM_SIZE 3000 | |
void interpret(char* instruction) { | |
unsigned char* tape = (unsigned char*)malloc(MEM_SIZE * sizeof(char)); | |
unsigned char* ptr = &tape[0]; | |
for (;*instruction; ++instruction) { | |
switch(*instruction) { | |
case '>': | |
ptr++; | |
break; | |
case '<': | |
ptr--; | |
break; | |
case '+': | |
++*ptr; | |
break; | |
case '-': | |
--*ptr; | |
break; | |
case ',': | |
*ptr = getchar(); | |
break; | |
case '.': | |
putchar(*ptr); | |
break; | |
case '[': | |
if(!*ptr) { | |
size_t loop = 1; | |
while (loop) { | |
++instruction; | |
if (*instruction == ']') --loop; | |
if (*instruction == '[') ++loop; | |
} | |
} | |
break; | |
case ']': | |
if (*ptr) { | |
size_t loop = 1; | |
while (loop) { | |
--instruction; | |
if (*instruction == '[') --loop; | |
if (*instruction == ']') ++loop; | |
} | |
} | |
break; | |
default: | |
printf("Invalid character '%c'\n", *ptr); | |
} | |
} | |
free(tape); | |
} | |
int main(int args, char* arg[]){ | |
interpret("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment