Skip to content

Instantly share code, notes, and snippets.

@bowbahdoe
Created May 18, 2016 23:06
Show Gist options
  • Select an option

  • Save bowbahdoe/a6836eece2f27f68b96b7b11dd48d6fa to your computer and use it in GitHub Desktop.

Select an option

Save bowbahdoe/a6836eece2f27f68b96b7b11dd48d6fa to your computer and use it in GitHub Desktop.
import sys
import os
filename = sys.argv[1]
c_code ='''
#include <stdlib.h>
#include <stdio.h>
int main(){
int cell_size = 1000;
char * ptr = (char*)(calloc(cell_size * sizeof(char), 0));
%s
return 0;
}
'''
code_equivalance = {
'+': '(*ptr)++;\n',
'-': '(*ptr)--;\n',
'>': 'ptr++;\n',
'<': 'ptr--;\n',
',': '(*ptr) = getchar();\n',
'.': 'putchar(*ptr);\n',
'*': 'printf(\"%d\", (*(int*)(ptr)));\n',
'!': 'printf("\\n");\n',
'[': 'while(*ptr){\n',
']': '}\n',
'@': "",
'$': "",
'^': "",
'~': '(*(int*)(ptr)) = 0;\n',
'(': 'if(*ptr){\n',
')': '}else{\n'
}
def loadbf(filename):
data = ''
with open(filename) as bffile:
for line in bffile:
data += line
data = [character for character in data if character in code_equivalance.keys()]
code=''
for i in data:
code+=i
return code
symbols = loadbf(filename)
code = ''
print symbols
for symbol in symbols:
code += code_equivalance[symbol]
c_code = c_code % code
with open("c_code.c", "w") as code_file:
code_file.write(c_code)
os.system("gcc c_code.c -o bf")
os.system("rm c_code.c")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment