Skip to content

Instantly share code, notes, and snippets.

@Job79
Last active January 23, 2022 18:56
Show Gist options
  • Save Job79/5ca5f965dfd590d8422078507888e384 to your computer and use it in GitHub Desktop.
Save Job79/5ca5f965dfd590d8422078507888e384 to your computer and use it in GitHub Desktop.
Small Brainfuck interpreter written in c#
static void Run(char[] c)
{
var s = new List<byte>{0};
int p = 0, bc = 0;
for (int i = 0; i < c.Length; i++)
{
if (c[i] == '>' && s.Count == ++p) s.Add(0);
else if (c[i] == '<') p--;
else if (c[i] == '+') s[p]++;
else if (c[i] == '-') s[p]--;
else if (c[i] == '.') Console.Write((char)s[p]);
else if (c[i] == ',') s[p] = (byte) Console.ReadKey().KeyChar;
else if (c[i] == '[' && s[p] == 0 && bc++ != null)
while (c[i] != ']' || bc != 0) bc += c[++i] == '[' ? 1 : c[i] == ']' ? -1 : 0;
else if (c[i] == ']' && s[p] != 0 && bc++ != null)
while (c[i] != '[' || bc != 0) bc += c[--i] == ']' ? 1 : c[i] == '[' ? -1 : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment