Skip to content

Instantly share code, notes, and snippets.

@Grumblesaur
Created November 5, 2016 20:52
Show Gist options
  • Save Grumblesaur/380488b98fabe59c63f4c2c75a32442d to your computer and use it in GitHub Desktop.
Save Grumblesaur/380488b98fabe59c63f4c2c75a32442d to your computer and use it in GitHub Desktop.
Brainfuck to C Transpiler
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