Skip to content

Instantly share code, notes, and snippets.

@gszauer
Created October 11, 2014 02:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gszauer/f1a2e0beef15a73ac107 to your computer and use it in GitHub Desktop.
Save gszauer/f1a2e0beef15a73ac107 to your computer and use it in GitHub Desktop.
Simple 100 line C# brainfuck interpreter
using System;
namespace Brainfuck {
class MainClass {
public static void Main (string[] args) {
Console.WriteLine ("Enter Command Buffer: ");
string commandBuffer = Console.ReadLine ();
int[] memory = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int memoryPointer = 0;
Console.ForegroundColor = ConsoleColor.Blue;
for (int i = 0; i < commandBuffer.Length; ++i) {
if (commandBuffer [i] == ',') {
Console.Clear ();
Console.Write ("Provide input: ");
string input = Console.ReadLine ();
memory [memoryPointer] = System.Convert.ToInt32 (input);
}
else if (commandBuffer [i] == '.') {
Console.WriteLine (memory [memoryPointer]);
}
else if (commandBuffer [i] == '<') {
memoryPointer--;
}
else if (commandBuffer [i] == '>') {
memoryPointer++;
}
else if (commandBuffer [i] == '+') {
memory [memoryPointer] += 1;
}
else if (commandBuffer [i] == '-') {
memory [memoryPointer] -= 1;
}
else if (commandBuffer [i] == '[') {
if (memory [memoryPointer] == 0) {
int skip = 0;
int ptr = i + 1;
while (commandBuffer[ptr] != ']' || skip > 0) {
if (commandBuffer [ptr] == '[') {
skip += 1;
}
else if (commandBuffer [ptr] == ']') {
skip -= 1;
}
ptr += 1;
i = ptr;
}
}
}
else if (commandBuffer [i] == ']') {
if (memory [memoryPointer] != 0) {
int skip = 0;
int ptr = i - 1;
while (commandBuffer[ptr] != '[' || skip > 0) {
if (commandBuffer [ptr] == ']') {
skip += 1;
}
else if (commandBuffer [ptr] == '[') {
skip -= 1;
}
ptr -= 1;
i = ptr;
}
}
}
Console.Clear ();
for (int j = 0; j < memory.Length; ++j) {
if (j == memoryPointer) {
Console.ForegroundColor = ConsoleColor.Red;
}
else {
Console.ForegroundColor = ConsoleColor.Blue;
}
Console.Write (memory [j] + " ");
}
Console.WriteLine ("\n");
for (int j = 0; j < commandBuffer.Length; ++j) {
if (j == i) {
Console.ForegroundColor = ConsoleColor.Red;
}
else {
Console.ForegroundColor = ConsoleColor.Blue;
}
Console.Write (commandBuffer [j] + " ");
}
System.Threading.Thread.Sleep (1000);
}
Console.ReadLine ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment