Skip to content

Instantly share code, notes, and snippets.

@0xbb
Created May 19, 2015 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xbb/27edf59b21d827360402 to your computer and use it in GitHub Desktop.
Save 0xbb/27edf59b21d827360402 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in Python
#!/usr/bin/env python3
# Usage: ./bfi.py source.bf
import sys
with open(sys.argv[1]) as f:
py_program = "import sys;cells = [0]*30000;ptr = 0\n"
level = 0
for i in f.read():
py_program += " "*level
if i == '>':
py_program += "ptr += 1"
elif i == '<':
py_program += "ptr -= 1"
elif i == '+' or i == '-':
py_program += "cells[ptr] = (cells[ptr]" + i + "1) % 256"
elif i == '.':
py_program += "sys.stdout.write(chr(cells[ptr]));sys.stdout.flush()"
elif i == ',':
py_program += "cells[ptr] = ord(sys.stdin.read(1))"
elif i == '[':
py_program += "while cells[ptr]:"
level += 1
elif i == ']':
py_program +="pass"
level -=1
py_program += "\n"
exec(py_program)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment