Skip to content

Instantly share code, notes, and snippets.

@dz1984
Last active July 1, 2017 01:23
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 dz1984/05e4c6cc6e72c563fd4e7af03718734f to your computer and use it in GitHub Desktop.
Save dz1984/05e4c6cc6e72c563fd4e7af03718734f to your computer and use it in GitHub Desktop.
A simple brainfuck interpreter.
#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