Skip to content

Instantly share code, notes, and snippets.

@mhay10
Created May 8, 2022 04:05
Show Gist options
  • Select an option

  • Save mhay10/6aaf9cc7fcd1974f61a857fb7b8d5d9d to your computer and use it in GitHub Desktop.

Select an option

Save mhay10/6aaf9cc7fcd1974f61a857fb7b8d5d9d to your computer and use it in GitHub Desktop.
A brainfuck interpreter I wrote in C++ for fun.
#include <fstream>
#include <iostream>
std::string minimize(std::string s) {
std::string res;
for (char c : s)
if ((std::string("[],.<>+-")).find(c) != std::string::npos)
res += c;
return res;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <file>\n";
return 1;
}
std::ifstream file(argv[1]);
if (!file.is_open()) {
std::cout << "Could not open file \"" << argv[1] << "\"\n";
return 1;
}
char c;
std::string contents;
while (file.get(c)) contents += c;
std::string compact = minimize(contents);
const char* code = compact.c_str();
const char* ctr = code;
char mem[30000];
std::fill(mem, mem + 30000, 0);
char* ptr = mem;
int pos = 0;
int i;
while (*ctr) {
switch (*ctr) {
case '>':
ptr++;
if (++pos == 30000) {
std::cout << "Memory overflow\n";
return 1;
}
break;
case '<':
ptr--;
if (--pos == -1) {
std::cout << "Memory underflow\n";
return 1;
}
break;
case '+':
if (++*ptr > 255) *ptr = 0;
break;
case '-':
if (--*ptr < 0) *ptr = 255;
break;
case '.':
std::cout << *ptr;
break;
case ',':
std::cin >> *ptr;
break;
case '[':
i = 1;
if (*ptr == 0) {
do {
ctr++;
if (*ctr == '[')
i++;
else if (*ctr == ']')
i--;
} while (i != 0);
}
break;
case ']':
i = 0;
do {
if (*ctr == '[')
i++;
else if (*ctr == ']')
i--;
ctr--;
} while (i != 0);
}
ctr++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment