How does the Brainfuck Hello World actually work?

后端 未结 6 1573
长情又很酷
长情又很酷 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:38

    Brainfuck same as its name. It uses only 8 characters > [ . ] , - + which makes it the quickest programming language to learn but hardest to implement and understand. ….and makes you finally end up with f*cking your brain.

    It stores values in array: [72 ][101 ][108 ][111 ]

    let, initially pointer pointing to cell 1 of array:

    1. > move pointer to right by 1

    2. < move pointer to left by 1

    3. + increment the value of cell by 1

    4. - increment the value of element by 1

    5. . print value of current cell.

    6. , take input to current cell.

    7. [ ] loop, +++[ -] counter of 3 counts bcz it have 3 ′+’ before it, and - decrements count variable by 1 value.

    the values stored in cells are ascii values:

    so referring to above array: [72 ][101 ][108 ][108][111 ] if you match the ascii values you’ll find that it is Hello writtern

    Congrats! you have learned the syntax of BF

    ——-Something more ———

    let us make our first program i.e Hello World, after which you’re able to write your name in this language.

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

    breaking into pieces:

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

    Makes an array of 4 cells(number of >) and sets a counter of 10 something like : —-psuedo code—-

    array =[7,10,3,1]
    i=10
    while i>0:
     element +=element
     i-=1
    

    because counter value is stored in cell 0 and > moves to cell 1 updates its value by+7 > moves to cell 2 increments 10 to its previous value and so on….

    <<< return to cell 0 and decrements its value by 1

    hence after loop completion we have array : [70,100,30,10]

    >++. 
    

    moves to 1st element and increment its value by 2(two ‘+’) and then prints(‘.’) character with that ascii value. i.e for example in python: chr(70+2) # prints 'H'

    >+.
    

    moves to 2nd cell increment 1 to its value 100+1 and prints(‘.’) its value i.e chr(101) chr(101) #prints ‘e’ now there is no > or < in next piece so it takes present value of latest element and increment to it only

    +++++ ++..
    

    latest element = 101 therefore, 101+7 and prints it twice(as there are two‘..’) chr(108) #prints l twice can be used as

    for i in array:
        for j in range(i.count(‘.’)):
               print_value
    

    ———Where is it used?——-

    It is just a joke language made to challenge programmers and is not used practically anywhere.

提交回复
热议问题