How does the Brainfuck Hello World actually work?

后端 未结 6 1619
长情又很酷
长情又很酷 2021-01-29 17:38

Someone sent this to me and claimed it is a hello world in Brainfuck (and I hope so...)

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


        
6条回答
  •  逝去的感伤
    2021-01-29 18:22

    Wikipedia has a commented version of the code.

    +++++ +++++             initialize counter (cell #0) to 10
    [                       use loop to set the next four cells to 70/100/30/10
        > +++++ ++              add  7 to cell #1
        > +++++ +++++           add 10 to cell #2 
        > +++                   add  3 to cell #3
        > +                     add  1 to cell #4
        <<<< -                  decrement counter (cell #0)
    ]                   
    > ++ .                  print 'H'
    > + .                   print 'e'
    +++++ ++ .              print 'l'
    .                       print 'l'
    +++ .                   print 'o'
    > ++ .                  print ' '
    << +++++ +++++ +++++ .  print 'W'
    > .                     print 'o'
    +++ .                   print 'r'
    ----- - .               print 'l'
    ----- --- .             print 'd'
    > + .                   print '!'
    > .                     print '\n'
    

    To answer your questions, the , and . characters are used for I/O. The text is ASCII.

    The Wikipedia article goes on in some more depth, as well.

    The first line initialises a[0] = 10 by simply incrementing ten times from 0. The loop from line 2 effectively sets the initial values for the array: a[1] = 70 (close to 72, the ASCII code for the character 'H'), a[2] = 100 (close to 101 or 'e'), a[3] = 30 (close to 32, the code for space) and a[4] = 10 (newline). The loop works by adding 7, 10, 3, and 1, to cells a[1], a[2], a[3] and a[4] respectively each time through the loop - 10 additions for each cell in total (giving a[1]=70 etc.). After the loop is finished, a[0] is zero. >++. then moves the pointer to a[1], which holds 70, adds two to it (producing 72, which is the ASCII character code of a capital H), and outputs it.

    The next line moves the array pointer to a[2] and adds one to it, producing 101, a lower-case 'e', which is then output.

    As 'l' happens to be the seventh letter after 'e', to output 'll' another seven are added (+++++++) to a[2] and the result is output twice.

    'o' is the third letter after 'l', so a[2] is incremented three more times and output the result.

    The rest of the program goes on in the same way. For the space and capital letters, different array cells are selected and incremented or decremented as needed.

提交回复
热议问题