An official interpreter for the brainfuck language:
Brainfuck is a language designed according to the concept of "Turing complete". Its main design idea is to use the smallest concept to implement a "simple" language, the brainfuck language has only eight symbols, and all the operations are completed by the combination of these eight symbols.
Brainfuck is based on a simple machine model. In addition to eight commands, this machine also includes: an array in bytes, initialized to zero, a pointer to the array (the first byte pointing to the array at the beginning), and two byte streams used for input and output.
Because brainfuck has only eight commands and does not have keywords, it does not allow custom identifiers,
Therefore, it is very simple to implement the compiler. Anyone who is new to C can compile it by themselves. Although everyone here can compile one by themselves, in order to attract everyone's interest, here is an official version:
# Include <stdio. h>;
Int P, R, Q;
Char A [5000], F [5000], B, O, * s = F;
Void interpret (char * C)
{
Char * D;
R ++;
While (* c ){
// If (strchr ("<>; +-,. []/n", * C) printf ("% C", * C );
Switch (O = 1, * C ++ ){
Case '<': p --; break;
Case '>': P ++; break;
Case '+': A [p] ++; break;
Case '-': A [p] --; break;
Case '.': putchar (A [p]); fflush (stdout); break;
Case ',': A [p] = getchar (); fflush (stdout); break;
Case '[':
For (B = 1, D = C; B & * C; C ++)
B + = * c = '[', B-= * c = ']';
If (! B ){
C [-1] = 0;
While (A [p])
Interpret (d );
C [-1] = ']';
Break;
}
Case ']':
Puts ("unbalanced brackets"), exit (0 );
Case '#':
If (q> 2)
Printf ("% 2D % 2D % 2D % 2D % 2D % 2D % 2D % 2D % 2D % 2D/n % * s/n ",
* A, a [1], a [2], a [3], a [4], a [5], a [6], a [7], A [8], a [9], 3 * P + 2, "^ ");
Break;
Default: O = 0;
}
If (p <0 | P> 100)
Puts ("Range Error"), exit (0 );
}
R --;
// Chkabort ();
}
Main (INT argc, char * argv [])
{
File * z;
Q = argc;
If (Z = fopen (argv [1], "R ")){
While (B = GETC (z)> 0)
* S ++ = B;
* S = 0;
Interpret (f );
}
}
The following is a brainfuck program for printing Hello World:
++ [++ <-]> ++.> +. ++ .. ++.> ++. <++...>. ++. ------. --------.> +.>.
Compile the above brainfuck into executable files, such as test, and then store the above brainfuck Hello World Program in a file, such as hello. B
Then run./test hello. B to output Hello world.
Brainfuck Syntax:
Character meaning
>; Pointer plus one
<Pointer minus one
+ The value of the byte pointed to by the pointer plus one
-The value of the byte pointed to by the pointer minus one
. Output the unit content pointed to by the pointer (ASCII code)
, The input content to the Unit pointed to by the pointer (ASCII code)
[If the unit value pointed to by the pointer is zero, jump forward to the corresponding] The next command of the command
] If the unit value pointed to by the pointer is not zero, jump back to the corresponding [Command's next command
By http://fayaa.com/code/view/9975/