Monday, September 22, 2014

A Brainfuck Interpreter in C

Brainfuck is an esoteric programming language noted for its extreme minimalism. The language consists of only eight simple commands and an instruction pointer. It is designed to challenge and amuse programmers, and was not made to be suitable for practical use. It was created in 1993 by Urban Müller - Wikipedia

In short brainfuck has eight commands or instructions:

+ : Increments the value at the current cell by one.
- : Decrements the value at the current cell by one.
> : Moves the data pointer to the next cell (cell on the right).
< : Moves the data pointer to the previous cell (cell on the left).
. : Prints the ASCII value at the current cell (i.e. 65 = 'A').
, : Reads a single input character into the current cell.
[ : If the value at the current cell is zero, skips to the corresponding ] .
    Otherwise, move to the next instruction.
] : If the value at the current cell is zero, move to the next instruction.
    Otherwise, move backwards in the instructions to the corresponding [ . 

Here is a basic brainfuck interpreter in C that takes brainfuck code, works on it and produces the intended output. The implementation uses a recursive approach (why ? because brainfuck) and a stack for interpreting the brainfuck code. The examples include a multiplication code, addition of a series of numbers and some ASCII printing. The code is compiled and tested on  Visual C++ 2010 Express.There are several other ways to interpret brainfuck code, this is just one of those...

Next i will try to see the possiblity of implementing this on an FPGA. 

No comments: