forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase32.py
46 lines (37 loc) · 1.39 KB
/
base32.py
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
"""
Base32 encoding and decoding
https://en.wikipedia.org/wiki/Base32
"""
B32_CHARSET="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
defbase32_encode(data: bytes) ->bytes:
"""
>>> base32_encode(b"Hello World!")
b'JBSWY3DPEBLW64TMMQQQ===='
>>> base32_encode(b"123456")
b'GEZDGNBVGY======'
>>> base32_encode(b"some long complex string")
b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY='
"""
binary_data="".join(bin(ord(d))[2:].zfill(8) fordindata.decode("utf-8"))
binary_data=binary_data.ljust(5* ((len(binary_data) //5) +1), "0")
b32_chunks=map("".join, zip(*[iter(binary_data)] *5))
b32_result="".join(B32_CHARSET[int(chunk, 2)] forchunkinb32_chunks)
returnbytes(b32_result.ljust(8* ((len(b32_result) //8) +1), "="), "utf-8")
defbase32_decode(data: bytes) ->bytes:
"""
>>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====')
b'Hello World!'
>>> base32_decode(b'GEZDGNBVGY======')
b'123456'
>>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=')
b'some long complex string'
"""
binary_chunks="".join(
bin(B32_CHARSET.index(_d))[2:].zfill(5)
for_dindata.decode("utf-8").strip("=")
)
binary_data=list(map("".join, zip(*[iter(binary_chunks)] *8)))
returnbytes("".join([chr(int(_d, 2)) for_dinbinary_data]), "utf-8")
if__name__=="__main__":
importdoctest
doctest.testmod()