Saturday, July 24, 2010

brainfuck Overview

brainfuck is, perhaps, the most famous of esoteric programming languages.

I will give you a quick overview here of the syntax (such as there is) and instruction set of this language, after the jump.



A brainfuck execution creates a virtual machine of 65,536 cells, each of which can contain any number between 0 and 255 (inclusive), and are initially set to 0. There is also a cell-pointer, which initially points to the first cell.

The language only has eight instructions, which come in pairs. The first three pairs are easy to describe:
  • arithmetic
    • + increases the value of the current cell
    • - decreases the value of the current cell
  • pointer arithmetic
    •  > moves the pointer one cell to the right
    •  < moves the pointer one cell to the left
  • input/output
    • . outputs the ASCII character to standard out corresponding to the contents of the currently pointed cell
    • , inputs a character from standard in, and puts the ascii code into the currently pointed cell
The final two instructions are for the forming of loops. They are open and closed square brackets. In order for a brainfuck programme to be valid, the open and closed brackets must match up in the traditional way. Then the instructions do the following:
  • loops
    • [ checks if the value of the currently pointed cell is zero. If it is, it jumps to the instruction after the corresponding ], or else it continues.
    • ] checks if the value of the currently pointed cell is non-zero. If it is, it jumps to the instruction after the corresponding [, or else it continues.
A brief but common example of a loop is [->+<]. Suppose we are pointing to cell 92 when we reach this loop, and let's see what happens:
  • If the current content of cell 92 is 0, then when we reach the open square bracket, the loop is skipped, and so nothing happens
  • If the current content of cell 92 is 1, then when we reach the open square bracket, we enter the loop. Then we decrement cell 92, move to cell 93, increment it, and return to cell 92. Since now the value of cell 92 is 0, we exit the loop. This means that we increment cell 93 by 1, and set cell 92 to 0.
  • Similarly, if the current content of cell 92 is 2, we decrement cell 92, increment cell 93 and return to cell 92, and then since we have a non-zero value in cell 92, we repeat the loop. Thus we increment cell 93 by 2 and set cell 92 to 0.
It is clear to see that [->+<] increments the following cell by the value in the current cell, and sets the current cell to 0. Brainfuck is unusual among programming languages in that it is very easy to directly replace its instructions with those in other programming languages to get an identical program. For example, this Python script converts Brainfuck to C++. In particular, it changes this fairly compact Brainfuck hello world into this monstrosity.

No comments:

Post a Comment