IVY864

Brainfuck

Brainfuck is an esoteric programming language created with the goal of implementing the smallest possible compiler.

Memory

Brainfuck's memory is formatted as an array of memory cells which are initialized to 0. The exact number of cells is dependent on the implementation. There is a pointer, which starts at the first cell. The cell being pointed to is the cell that gets operated on.

Instructions

Brainfuck only has 8 instructions. All characters that are not the 8 brainfuck instructions are ignored.

Instruction Function
> Increment position of pointer
< Decrement position of pointer
+ Increment value of cell at pointer
- Decrement value of cell at pointer
[ Start loop
] End loop1
. Print value at pointer2
, Take 1 character as input3

1. see loops section below

2. the character that gets output is the value of the cell in ascii. ie. a cell set to 97 would output 'a'

3. like with output, the ascii value of the input character is taken and the cell at the pointer is set to that value. For example, if 'a' is taken as input, the cell at the pointer would be set to 97

Loops

Loops in brainfuck are started with the '[' operator. When a ']' is reached, the value at the current cell is checked. If it is equal to 0, the program continues. Otherwise, the loop loops. Loops are essential in brainfuck, as it significantly minimizes the number of characters the programmer needs to type.

Loop example

++++++++    set value at pointer to 8
[           start loop
    >       move pointer forwards
    ++++++  increment cell by 8
    <-      move pointer back to first cell and decrement it by 1
]
>.          move pointer over 1 cell and output value

This is a pretty common pattern in brainfuck, which allows you to effectively multiply 2 numbers. In this example, we are setting the first cell to 8, and then adding 6 to the second cell on every iteration of the loop. At the end of the loop we go back to the first cell and subtract 1. the 8th time we do this, the first cell will be 0, so the loop will end.

Nesting Loops

By nesting loops, we can multiply even more numbers.

++++
[
    >
    ++++
    [
        >
        ++++
        <-
    ]
    <-
]
>>.

This program puts a loop inside of a loop, and gives us a final value of 64 in the second cell, resulting in an output of '@'

Brainfuck Resources

More Information

Interpreters

Theres a lot of brainfuck interpreters out there. this is one that runs in a browser that I like. This is one that I wrote in java.

Other stuff

https://github.com/rdebath/Brainfuck

I don't really know how to categorize this, but its a github repository with a huge amount of brainfuck related things, including the original brainfuck interpreter.