Skip to content

Instantly share code, notes, and snippets.

@OrigamiTech
Created January 21, 2011 15:28
Show Gist options
  • Save OrigamiTech/789838 to your computer and use it in GitHub Desktop.
Save OrigamiTech/789838 to your computer and use it in GitHub Desktop.
BrainFuck interpreter in C#
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