Labels

Arduino (1) Brainf**k (1) Bugs (3) C (1) HTML (1) Install (3) Linux (27) Maths (1) Python (12) Raspberry Pi (4)

Friday, 14 July 2017

Programming in Brainf**k


Brainf**k is a minimalistic programming language that consists of 8 commands and a instruction pointer. It is known as a esoteric programming language as it isn't intended for practical use but more as a joke.

The 8 commands are:
+: Increment the current cell by one
-: Decrement the current cell by one
.: Print the ASCII value of the current cell
,: Read a input character into the current cell
[: Skips to corresponding ] if the current cell is 0
]: Skips to the corresponding [ if the current cell is not 0
<: Moves the instruction pointer 1 back
>: Moves the instruction pointer 1 forward

Example program:
We are going to print the letter "A" which has a value of 65 is ASCII. This can be done two ways.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
This increments the current cell 65 times and then prints the ASCII value of the current cell
As you can probably see this isn't a very good way to achieve this.

Python representative code:
cell1=65
print(chr(cell1))

We are going to use a loop to increment it to 65.
++++++++
[
>++++++++
<->+
.
Line 1: Increment the first cell to 8
Line 2: Check if the value of the current cell is 0, if true skip to ] otherwise go to the next instruction
Line 3: Move the instruction pointer 1 forward and increment it to 8.
Line 4: Move the instruction pointer 1 backward and decrement it by 1.
Line 5: Check if the value of the current cell is 0, if true move to next instruction otherwise skip back to [
Line 6: Move the instruction pointer 1 forward and increment it by 1
Line 7: Print the ASCII value of the current cell

Python representative code:
cell1=8
while(cell1 != 0):
    cell2 = cell2 + 8
    cell1 = cell1 - 1
cell2 = cell2 + 1
print(chr(cell2))