How to calculate the sum of 2 numbers with BrainFu

2019-01-17 17:54发布

I'm trying to write a program with BrainFuck that can read two numbers up to 9, calculate the sum of them and then print the result out, e.g. 3 & 5 give the result 8 .

I'm just trying to understand the BF language but it looks much harder than I thought it would be.

标签: brainfuck
7条回答
Evening l夕情丶
2楼-- · 2019-01-17 18:59

Think of the language as a huge tape (30K bytes long) where you can read, write and move forward or backward and increment/decrement one cell at a time (each cell being 1 byte, so you effectively have 30K cells). Optionally, you can read in and write out stuff that the byte stream holds(in ASCII form). Assuming that you know the basic operators, a program to sum two numbers should go along the following lines:

,       ; read character and store it in p1
>       ; move pointer to p2 (second byte)
,       ; read character and store it in p2
[           ; enter loop
    <       ; move to p1
    +       ; increment p1
    >       ; move to p2
    -       ; decrement p2
]           ; we exit the loop when the last cell is empty
<       ; go back to p1
------------------------------------------------ ; subtract 48 (ie ASCII char code of '0')
.       ; print p1
查看更多
登录 后发表回答