Created
May 19, 2015 17:03
-
-
Save 0xbb/88427075e56efdc3e6e9 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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