Skip to content

Instantly share code, notes, and snippets.

@0xbb
Created May 19, 2015 17:03
Show Gist options
  • Save 0xbb/88427075e56efdc3e6e9 to your computer and use it in GitHub Desktop.
Save 0xbb/88427075e56efdc3e6e9 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:
program = f.read()
cells = [0]*30000
ptr = 0
pc = 0
label_stack = []
while pc < len(program):
i = program[pc]
if i == '>':
ptr += 1
elif i == '<':
ptr -= 1
elif i == '+':
cells[ptr] = (cells[ptr] + 1) % 256
elif i == '-':
cells[ptr] = (cells[ptr] - 1) % 256
elif i == '.':
sys.stdout.write(chr(cells[ptr]))
sys.stdout.flush()
elif i == ',':
cells[ptr] = ord(sys.stdin.read(1))
elif i == '[':
if cells[ptr] == 0:
c = 0
while True:
pc += 1
if program[pc] == '[':
c += 1
elif program[pc] == ']':
c -= 1
if c == -1:
break
else:
label_stack.append(pc)
elif i == ']':
pc = label_stack.pop() - 1
pc += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment