How does the Brainfuck Hello World actually work?

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

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

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


        
6条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 18:24

    To answer the question of how it knows what to print, I have added the calculation of ASCII values to the right of the code where the printing happens:

    > just means move to the next cell
    < just means move to the previous cell
    + and - are used for increment and decrement respectively. The value of the cell is updated when the increment/decrement happens
    
    +++++ +++++             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' (ascii: 70+2 = 72) //70 is value in current cell. The two +s increment the value of the current cell by 2
    
    > + .                   print 'e' (ascii: 100+1 = 101)
    
    +++++ ++ .              print 'l' (ascii: 101+7 = 108)
    
    .                       print 'l' dot prints same thing again
    
    +++ .                   print 'o' (ascii: 108+3 = 111)
    
    > ++ .                  print ' ' (ascii: 30+2 = 32)
    
    << +++++ +++++ +++++ .  print 'W' (ascii: 72+15 = 87)
    
    > .                     print 'o' (ascii: 111)
    
    +++ .                   print 'r' (ascii: 111+3 = 114)
    
    ----- - .               print 'l' (ascii: 114-6 = 108)
    
    ----- --- .             print 'd' (ascii: 108-8 = 100)
    
    > + .                   print '!' (ascii: 32+1 = 33)
    
    > .                     print '\n'(ascii: 10)
    

提交回复
热议问题