forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase85.py
More file actions
Latest commit
58 lines (46 loc) · 1.82 KB
/
Copy pathbase85.py
File metadata and controls
58 lines (46 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Base85 (Ascii85) encoding and decoding
https://en.wikipedia.org/wiki/Ascii85
"""
def_base10_to_85(d: int) ->str:
return"".join(chr(d%85+33)) +_base10_to_85(d//85) ifd>0else""
def_base85_to_10(digits: list) ->int:
returnsum(char*85**ifori, charinenumerate(reversed(digits)))
defascii85_encode(data: bytes) ->bytes:
"""
>>> ascii85_encode(b"")
b''
>>> ascii85_encode(b"12345")
b'0etOA2#'
>>> ascii85_encode(b"base 85")
b'@UX=h+?24'
"""
binary_data="".join(bin(ord(d))[2:].zfill(8) fordindata.decode("utf-8"))
null_values= (32* ((len(binary_data) //32) +1) -len(binary_data)) //8
binary_data=binary_data.ljust(32* ((len(binary_data) //32) +1), "0")
b85_chunks= [int(_s, 2) for_sinmap("".join, zip(*[iter(binary_data)] *32))]
result="".join(_base10_to_85(chunk)[::-1] forchunkinb85_chunks)
returnbytes(result[:-null_values] ifnull_values%4!=0elseresult, "utf-8")
defascii85_decode(data: bytes) ->bytes:
"""
>>> ascii85_decode(b"")
b''
>>> ascii85_decode(b"0etOA2#")
b'12345'
>>> ascii85_decode(b"@UX=h+?24")
b'base 85'
"""
null_values=5* ((len(data) //5) +1) -len(data)
binary_data=data.decode("utf-8") +"u"*null_values
b85_chunks=map("".join, zip(*[iter(binary_data)] *5))
b85_segments= [[ord(_s) -33for_sinchunk] forchunkinb85_chunks]
results= [bin(_base85_to_10(chunk))[2::].zfill(32) forchunkinb85_segments]
char_chunks= [
[chr(int(_s, 2)) for_sinmap("".join, zip(*[iter(r)] *8))] forrinresults
]
result="".join("".join(char) forcharinchar_chunks)
offset=int(null_values%5==0)
returnbytes(result[: offset-null_values], "utf-8")
if__name__=="__main__":
importdoctest
doctest.testmod()