Created
November 5, 2016 20:52
-
-
Save Grumblesaur/380488b98fabe59c63f4c2c75a32442d to your computer and use it in GitHub Desktop.
Brainfuck to C Transpiler
This file contains hidden or 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
import sys | |
symbols = { | |
'>' : '++ptr;', | |
'<' : '--ptr;', | |
'+' : '++*ptr;', | |
'-' : '--*ptr;', | |
'.' : 'putchar(*ptr);', | |
',' : '*ptr = getchar();', | |
'[' : 'while(*ptr) {', | |
']' : '}' | |
} | |
with open(sys.argv[1]) as infile, open(sys.argv[2], 'w') as outfile: | |
# indent output lines of C code | |
depth = 1; | |
# C program boilerplate | |
outfile.write("#include <stdio.h>\n") | |
outfile.write("int main() {\n") | |
outfile.write("\tchar array[%s] = {0};\n" % sys.argv[3]) | |
outfile.write("\tchar *ptr=array;\n") | |
# convert BF operations to equivalent C operation | |
for line in infile: | |
for char in line: | |
try: | |
outfile.write("\t" * depth) | |
outfile.write(symbols[char]) | |
depth += char == '[' | |
depth -= char == ']' | |
outfile.write("\n") | |
except: # unrecognized symbols in BF are comments. Print for debug purposes | |
print char, | |
outfile.write("}\n"); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment