Skip to content

Instantly share code, notes, and snippets.

@suxue
Created August 3, 2014 11:17
Show Gist options
  • Save suxue/b349889dbf32a9762e6b to your computer and use it in GitHub Desktop.
Save suxue/b349889dbf32a9762e6b to your computer and use it in GitHub Desktop.
brain fuck c++
// a simple brain-fuck interpretor
// see http:://en.wikipedia.org/wiki/Brainfuck
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <vector>
#define BUFSIZE 30000
class State {
private:
unsigned char data[BUFSIZE];
size_t dataptr;
std::vector<char> prg;
size_t prgptr;
void _exec();
public:
State() : dataptr(0) {
memset(data, 0, sizeof(data));
}
void read(char c) {
prg.push_back(c);
}
void exec() {
dataptr = 0;
prgptr = 0;
_exec();
}
char code() { return prg[prgptr]; }
};
void State::_exec()
{
while (prgptr < prg.size()) {
switch (code()) {
case '+':
data[dataptr]++; break;
case '-':
data[dataptr]--; break;
case '>':
dataptr++; break;
case '<':
dataptr--; break;
case '.':
putchar(data[dataptr]); break;
case ',':
data[dataptr] = getchar(); break;
case '[':
if (data[dataptr] == 0) {
int count = 0;
for (;;) {
prgptr += 1;
if (code() == '[') {
count += 1;
} else if (count == 0 && code() == ']') {
break;
} else if (count > 0 && code() == ']') {
count -= 1;
}
}
prgptr += 1;
continue;
} else {
break;
}
case ']':
if (data[dataptr] != 0) {
int count = 0;
for (;;) {
prgptr -= 1;
if (code() == ']') {
count += 1;
} else if (count == 0 && code() == '[') {
break;
} else if (count > 0 && code() == '[') {
count -= 1;
}
}
prgptr += 1;
continue;
} else {
break;
}
default:
break;
}
prgptr++;
}
}
int main(int argc, char *argv[])
{
assert(argc == 2);
State stat;
char *prg = argv[1];
while (*prg != 0) {
stat.read(*prg++);
}
stat.exec();
}
@suxue
Copy link
Author

suxue commented Aug 3, 2014

./bf  '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment