Created
January 21, 2011 15:28
-
-
Save OrigamiTech/789838 to your computer and use it in GitHub Desktop.
BrainFuck interpreter in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace BrainFrack | |
{ | |
class Program | |
{ | |
static unsafe void Main(string[] args) | |
{ | |
int size = 30000; | |
byte* ptr = (byte*)System.Runtime.InteropServices.Marshal.AllocCoTaskMem(size); | |
for (int i = 0; i < size; i++) *ptr++ = 0; | |
ptr -= size; | |
string code = Console.ReadLine(); | |
Console.Clear(); | |
run(code, ref ptr); | |
Console.ReadLine(); | |
} | |
static unsafe void run(string code, ref byte* ptr) | |
{ | |
for (int i = 0; i < code.Length; i++) | |
switch (code[i]) | |
{ | |
case '>': ptr++; break; | |
case '<': ptr--; break; | |
case '+': (*ptr)++; break; | |
case '-': (*ptr)--; break; | |
case '.': Console.Write((char)*ptr); break; | |
case ',': *ptr = (byte)Console.ReadKey(true).KeyChar; break; | |
case '[': | |
run(code.Substring(i + 1), ref ptr); | |
while (code[++i] != ']') ; break; | |
case ']': | |
if (*ptr == 0) return; | |
i = -1; break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment