Skip to content

Instantly share code, notes, and snippets.

@retep998
Created November 26, 2012 19:30
Show Gist options
  • Save retep998/4150116 to your computer and use it in GitHub Desktop.
Save retep998/4150116 to your computer and use it in GitHub Desktop.
Brainfuck
#include <iostream>
#include <fstream>
#include <filesystem>
#include <cstdint>
using namespace std;
using namespace std::tr2::sys;
size_t const msize = 0x100000;
void bf(path name, path input, path output) {
ifstream file(name, ios::binary);
ifstream inf(input, ios::binary);
ofstream outf(output, ios::binary);
size_t const fsize = file_size(name);
char * const program = new char[fsize + 1];
file.read(program, fsize);
size_t msx = 0;
for (size_t i = 0, ms = 0; i < fsize; ++i) {
if (program[i] == '[') {
++ms;
if (ms > msx) msx = ms;
} else if (program[i] == ']') --ms;
}
size_t * const stack = new size_t[msx];
size_t * const jump = new size_t[fsize];
for (size_t i = 0, j = 0; i < fsize; ++i) {
if (program[i] == '[') {
stack[j++] = i;
} else if (program[i] == ']') {
jump[i] = stack[--j];
jump[stack[j]] = i;
}
}
delete stack;
uint8_t * const memory = new uint8_t[msize];
for (size_t p = 0, m = 0;;) {
switch (program[p]) {
case '>':
++m;
break;
case '<':
--m;
break;
case '+':
++memory[m];
break;
case '-':
--memory[m];
break;
case ',':
memory[m] = static_cast<uint8_t>(inf.get());
break;
case '.':
outf.put(memory[m]);
break;
case '[':
if (!memory[m]) p = jump[p];
break;
case ']':
if (memory[m]) p = jump[p];
break;
case '\0':
delete[] program;
delete[] memory;
delete[] jump;
return;
default:
break;
}
++p;
}
}
int main() {
bf("program.bf", "input.txt", "output.txt");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment