Brainfuck part 1: what is it?
This article is part of a series on brainfuck, a weird programming language:
- Brainfuck part 1: what is it?
- Brainfuck part 2: an interpreter in JavaScript
- Brainfuck part 3: a brainfuck → JavaScript transpiler
Brainfuck is an esoteric programming language using only eight characters ><+-.,[]
.
It has no pratical use but it’s fun and challenges the mind.
Design
The language has only eight commands: the eight characters. Any other character is ignored and can be use for commenting.
The programming model is simple: you have a 30,000 cells data array and a pointer to the current cell. You can modify the value of this cell, print it (ASCII output) or replace it with the value of the keyboard input.
>
move the data pointer forward<
move the data pointer backward+
increments (+1) the current cell-
decrements (-1) the current cell.
outputs the current cell as an ASCII character,
reads one character from the input and writes it in the current cell[
makes the program jump to the instruction after the matching]
if the current cell’s value is 0.]
makes the program jump to the instruction after the matching[
if the current cell’s value is not 0.
Having only these commands is the ‘’fuck’’ part of brainfuck.
Examples
1 | ****************** |
Crazy, huh?
Now an “echo” program. It reads your input and just outputs it.
Serial version (reads all, prints all)
1 | > + mem = (O 1) ; you need a non zero cell to enter the loop |
Parallel version (reads one, prints one)
1
2
3
4
5
6, read first char
[ while the last read value is not 0
. print it
[-] reset the cell to 0
, read next char
]
Exercices
If you don’t think it’s fun, please close your browser. Otherwise, here are some exercices (the number of * indicates the difficulty):
How do you:
- Duplicate a cell? *
- Move a cell? *
- Add 2 cells? *
- Multiply 2 cells? **
Write the brainfuck equivalent of:
- If(a){code} *
- While(a && b){a—; b—} **
- If(x){code1}else{code2} *
Conclusion
Brainfuck is a well chosen name.
This article is part of a series on brainfuck, a weird programming language: