Created
November 10, 2012 04:09
-
-
Save agasiev/4049853 to your computer and use it in GitHub Desktop.
Simple 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 <string> | |
#include <string.h> | |
using namespace std; | |
int main(int, char **) { | |
const size_t memory_buffer_size = 30000; | |
unsigned char memory[memory_buffer_size]; | |
memset(memory, 0, memory_buffer_size); | |
short caretPos = 0, inputPos = 0; | |
std::string input; | |
std::cin >> input; | |
while (inputPos < input.length()) { | |
switch (input[inputPos]) { | |
case '>': | |
caretPos++; | |
break; | |
case '<': | |
caretPos--; | |
break; | |
case '+': | |
memory[caretPos]++; | |
break; | |
case '-': | |
memory[caretPos]--; | |
break; | |
case '.': | |
std::cout << memory[caretPos]; | |
break; | |
case ',': | |
int temp; | |
std::cin >> temp; | |
memory[caretPos] = temp % 256; | |
break; | |
case '[': | |
if (memory[caretPos] == 0) { | |
int bracketCnt = 1; | |
inputPos++; | |
while (bracketCnt && inputPos < input.length()) { | |
if (input[inputPos] == ']') bracketCnt--; | |
if (input[inputPos] == '[') bracketCnt++; | |
inputPos++; | |
} | |
assert(bracketCnt == 0); | |
} | |
break; | |
case ']': | |
if (memory[caretPos] != 0) { | |
int bracketCnt = 1; | |
inputPos--; | |
while (bracketCnt && inputPos < input.length()) { | |
if (input[inputPos] == ']') bracketCnt++; | |
if (input[inputPos] == '[') bracketCnt--; | |
inputPos--; | |
} | |
assert(bracketCnt == 0); | |
} | |
break; | |
default: | |
throw; | |
} | |
inputPos++; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment