根据维基百科上的内容随手写的一个BF解释器,输入有两个参数——程序代码、输入流,返回内容为输出流。输入、输出均为字符串。
字符
|
含义
|
C语言替换
|
---|---|---|
>
|
指针加一
|
++ptr;
|
<
|
指针减一
|
--ptr;
|
+
|
指针指向的字节的值加一
|
++*ptr;
|
-
|
指针指向的字节的值减一
|
--*ptr;
|
.
|
输出指针指向的单元内容(字符内码)
|
putchar(*ptr);
|
,
|
输入内容到指针指向的单元(字符内码)
|
*ptr=getchar();
|
[
|
如果指针指向的单元值为零,向后跳转到对应的]指令的次一指令处
|
while(*ptr){
|
]
|
如果指针指向的单元值不为零,向前跳转到对应的[指令的次一指令处
|
}
|
using System.Collections.Generic; namespace HumphreyJ.BF { public class Brainfuck { public static string eval(string code, string input) { string output = ""; int pointer_code = 0; int pointer_input = 0; int pointer_output = 0; Stack<int> stack = new Stack<int>(); //char array[infinitely large size] = {0}; List<char> array = new List<char> { '\0' }; //char* ptr = array; int ptr = 0; while (pointer_code < code.Length) { switch (code[pointer_code]) { case '>': { //++ptr; ++ptr; break; } case '<': { //--ptr; --ptr; break; } case '+': { //++*ptr; if (array.Count == ptr) { array.Add('\0'); } ++array[ptr]; break; } case '-': { //--*ptr; if (array.Count == ptr) { array.Add('\0'); } --array[ptr]; break; } case '.': { //putchar(*ptr); output += array[ptr]; pointer_output++; break; } case ',': { //*ptr = getchar(); array[ptr] = input[pointer_input++]; break; } case '[': { //while (*ptr) { if (array[ptr] != 0) { stack.Push(pointer_code); } else { int s = 1; while (s > 0) { pointer_code++; switch (code[pointer_code]) { case '[': { s++; break; } case ']': { s--; break; } } } } break; } case ']': { //} pointer_code = stack.Pop() - 1; break; } } pointer_code++; } return output; } } }