How to calculate the sum of 2 numbers with BrainFuck

Yahoo picture Yahoo · May 20, 2012 · Viewed 12.4k times · Source

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.

Answer

dirkgently picture dirkgently · May 20, 2012

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