Skip to content

Instantly share code, notes, and snippets.

@Mego
Created October 6, 2016 20:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mego/f395537ba949c6ab8034010a42d0a25c to your computer and use it in GitHub Desktop.
Save Mego/f395537ba949c6ab8034010a42d0a25c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
bits_to_symbols = {
0b000: '<',
0b001: '>',
0b010: '[',
0b011: ']',
0b100: '+',
0b101: '-',
0b110: ',',
0b111: '.',
}
symbols_to_bits = {value:key for (key, value) in bits_to_symbols.items()}
def bf_compress(code):
pad = len(code) % 8
lpad = pad//3
rpad = pad - lpad
b_code = '{:03b}'.format(symbols_to_bits['<'])*lpad
for c in code:
b_code += '{:03b}'.format(symbols_to_bits[c])
b_code += '0'*rpad
out = b''
for i in range(len(b_code)//8):
out += bytes([int(b_code[8*i:8*i+8], 2)])
return out
def bf_decompress(code):
b_code = ''.join("{:08b}".format(x) for x in code)
out = ''
for i in range(len(b_code)//3):
triplet = b_code[3*i:3*i+3]
if len(triplet) < 3:
break
out += bits_to_symbols[int(triplet, 2)]
return out.lstrip('<')
if __name__ == '__main__':
print(bf_compress('>+'))
print(bf_decompress(bf_compress('>+')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment