SHARE
TWEET

ff

a guest Apr 21st, 2017 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. import sys
  3.  
  4. codeOWED_CHARS = '<>+-.,[]'
  5.  
  6.  
  7. def load_brainfuck_code(filename):
  8.     with open(filename) as f:
  9.         raw_code = f.read()
  10.     code = [char for char in raw_code if char in codeOWED_CHARS]
  11.     return code
  12.  
  13.  
  14. def write_c_code_to_file(output, template):
  15.     with open(output, 'w') as f:
  16.         f.write(template)
  17.  
  18.  
  19. TEMPLATE = """
  20. #include <stdio.h>
  21.  
  22. int main(){
  23.  
  24. \tchar array[30000] = {0};
  25. \tchar *p=array+15000;
  26. %s
  27. \treturn 0;
  28. }
  29.  
  30.  
  31.  
  32.  
  33. """
  34.  
  35.  
  36. def main(filename, output):
  37.     bf_code = load_brainfuck_code(filename)
  38.     print bf_code
  39.     i = 0
  40.     c_code = []
  41.     code = []
  42.     last_char = ''
  43.     indent = 1
  44.     for char in bf_code:
  45.         if char == ']':
  46.             indent -= 1
  47.  
  48.         if last_char == char and last_char in '<>+-':
  49.             code[-1]['count'] += 1
  50.         else:
  51.             code.append({'code': char, 'indent': indent, 'count': 1})
  52.         last_char = char
  53.         if char == '[':
  54.             indent += 1
  55.  
  56.     for el in code:
  57.         c_code.append(el['indent'] * '\t' + el['code'])
  58.         c_code = TEMPLATE %'\n'.join(c_code)
  59.     write_c_code_to_file(output, c_code)
  60.  
  61.  
  62. if __name__ == '__main__':
  63.  
  64.     main(*sys.argv[1:])
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top