Skip to content

Instantly share code, notes, and snippets.

@wilfreddv
Created May 14, 2018 16:38
Show Gist options
  • Save wilfreddv/6951b70172702aa2d26120d1b20b831a to your computer and use it in GitHub Desktop.
Save wilfreddv/6951b70172702aa2d26120d1b20b831a to your computer and use it in GitHub Desktop.
Python script to turn text into the brainfuck code to print it
#!/usr/bin/python3
'''
Text-to-Brainfuck Generator
This program reads a textfile from stdin and
writes Brainfuck to stdout
The output only uses one block in a Brainfuck,
which is the currently selected block. It leaves
the block with value 0.
'''
from math import sqrt
from sys import stdin, stdout
def refactor(nr):
root = int(sqrt(nr))
rest = nr - (root**2)
return root, rest
def main():
old = 0
stdout.write('[-]')
for character in stdin.read():
_ord = ord(character)
if old == _ord:
stdout.write('.')
continue
deviation = _ord - old
mult = refactor(abs(deviation))
if 0 < deviation:
if deviation < 6:
stdout.write('{}.'.format('+'*deviation))
else:
stdout.write('>{}[<{}>-]<{}.'.format('+'*mult[0],'+'*mult[0],'+'*mult[1]))
else:
if deviation > -6:
stdout.write('{}.'.format('-'*abs(deviation)))
else:
stdout.write('>{}[<{}>-]<{}.'.format('+'*mult[0],'-'*mult[0],'-'*mult[1]))
old = _ord
stdout.write('[-]')
stdout.flush()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment