Last active
August 29, 2015 14:14
-
-
Save ikkentim/da2fc436a88a18dc79cf to your computer and use it in GitHub Desktop.
Basic brainfuck interpreter
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
#include <iostream> | |
#include <fstream> | |
using namespace std; | |
int main() { | |
ifstream codeFile ("main.bf"); | |
codeFile.seekg(0,ifstream::end); | |
int size=codeFile.tellg(); | |
codeFile.seekg(0); | |
char instructions[size]; | |
char memory[30000] = {'\0'}; | |
char input[128] = {'\0'}; | |
codeFile.read(instructions, size); | |
char *p = memory; | |
char *i = instructions; | |
char *c = input; | |
bool isLoop = false; | |
cout << "Start main.bf" << endl; | |
while(*i) { | |
bool enteredLoop = false; | |
switch(*i) { | |
case '>': | |
p++; | |
break; | |
case '<': | |
p--; | |
break; | |
case '+': | |
(*p)++; | |
break; | |
case '-': | |
(*p)--; | |
break; | |
case '.': | |
cout << *p; | |
break; | |
case ',': | |
while(!*c) { | |
cin >> input; | |
c = input; | |
} | |
*p = *c; | |
c++; | |
break; | |
case '[': | |
if(!*p) { | |
int find = 1; | |
do { | |
i++; | |
switch(*i) { | |
case '[': | |
find++; | |
break; | |
case ']': | |
find--; | |
break; | |
} | |
} while(find != 0); | |
} | |
else { | |
enteredLoop = true; | |
break; | |
} | |
break; | |
case ']': | |
if(*p) { | |
if(isLoop) { | |
cout << "INFINITE LOOP DETECTED" << endl; | |
return 0; | |
} | |
int find = 0; | |
do { | |
switch (*i) { | |
case ']': | |
find++; | |
break; | |
case '[': | |
find--; | |
break; | |
} | |
i--; | |
} while (find); | |
} | |
break; | |
} | |
isLoop = enteredLoop; | |
i++; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment