Advertisement
rilo

Brainfuck interpreter in PHP

Feb 5th, 2013
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.99 KB | None | 0 0
  1. <?
  2. $instructionpointer = 0;
  3. $memorypointer = 0;
  4. $memory = array();
  5. $callstack = array();
  6. // clear the memory cell array
  7. for ($i = 0; $i < 1000; $i++) {
  8.   $memory[$i] = 0;
  9. }
  10. $brainfuckcode = '++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.';
  11. $length = strlen($brainfuckcode);
  12. while ($instructionpointer < $length) {
  13.   $opcode = substr($brainfuckcode,$instructionpointer,1);
  14.   switch ($opcode) {
  15.     case "." :
  16.       echo chr($memory[$memorypointer]);
  17.       break;
  18.     case "+" :
  19.       $memory[$memorypointer]++;
  20.       break;
  21.     case "-" :
  22.       $memory[$memorypointer]--;
  23.       break;
  24.     case ">" :
  25.       $memorypointer++;
  26.       break;
  27.     case "<" :
  28.       $memorypointer--;
  29.       break;
  30.     case "[" :
  31.       $callstack[] = $instructionpointer;
  32.       break;
  33.     case "]" :
  34.       if ($memory[$memorypointer] != 0) {
  35.         $instructionpointer = $callstack[count($callstack)-1];
  36.       } else {
  37.         array_pop($callstack);
  38.       }
  39.       break;
  40.   }
  41.   $instructionpointer++;
  42. }
  43. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement