Skip to content

Instantly share code, notes, and snippets.

@Highstaker
Created November 17, 2016 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Highstaker/e34e72dbf7c76b825b6dc08794151af2 to your computer and use it in GitHub Desktop.
Save Highstaker/e34e72dbf7c76b825b6dc08794151af2 to your computer and use it in GitHub Desktop.
Ascii85 encoding-decoding
from itertools import groupby
def split_list(alist,max_size=1):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(alist), max_size):
yield alist[i:i+max_size]
def toAscii85(data):
result = []
for chunk in split_list(data, max_size=4):
# print(chunk)#debug
n_missing_chars = 4-len(chunk)
chunk += chr(0)*n_missing_chars
mult = sum(ord(i)*(256**n) for n, i in enumerate(reversed(chunk)))
# print(mult)#debug
templist = []
for _ in range(5):
temp = divmod(mult,85)
templist.append(chr(temp[1]+33))
mult = temp[0]
# print(templist)#debug
if all(i=="!" for i in templist) and not n_missing_chars:
result.append("z")
else:
result.extend(templist[::-1])
if n_missing_chars:
result = result[:-n_missing_chars]
return "<~" + "".join(result) + "~>"
def fromAscii85(data):
data = "".join(data[2:-2].split())#split() knows all the whitedata chars, so I don't have to input them
# print "data", data#debug
result = []
for bigger_grouped_chunk in groupby(data,key=lambda x: x=='z'):
print("bigger_grouped_chunk", bigger_grouped_chunk)#debug
if bigger_grouped_chunk[0]:
result.append(chr(0)*(4*sum(1 for _ in bigger_grouped_chunk[1])))
else:
for chunk in split_list(list(bigger_grouped_chunk[1]), max_size=5):
# print("chunk",chunk)#debug
n_missing_chars = 5-len(chunk)
chunk = chunk +["u"]*n_missing_chars
mult = sum((ord(i)-33)*(85**n) for n, i in enumerate(reversed(chunk)))
# print(mult)#debug
templist = []
for _ in range(4):
temp = divmod(mult,256)
templist.append(chr(temp[1]))
mult = temp[0]
# print(templist)#debug
result.extend(templist[::-1])
if n_missing_chars:
result = result[:-n_missing_chars]
return "".join(result)
# print(toAscii85('easy'))
# print(toAscii85('moderate'))
# print(toAscii85('somewhat difficult'))
# print(toAscii85('\x00'))
# print(fromAscii85("<~ARTY*~>"))
# print(fromAscii85('<~F)Po,GA(E,+Co1uAnbatCif~>'))
# print(list(fromAscii85('<~zz~>')))
print(list(fromAscii85("<~;f?Ma+92BAz!!$qJA0:jPzz!!!\"FATD^#F!(G_zz!,,qaAK_~>")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment