-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmbase32.py
54 lines (37 loc) · 972 Bytes
/
mbase32.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
47
48
49
50
51
52
53
54
# Copyright (c) 2014-2015 Sam Maloney.
# License: Public Domain.
charset = "13456789abcdefghijkmnopqrstuwxyz"
def encode(val):
result = ""
if not val:
return result
assert type(val) in (bytes, bytearray), type(val)
r = 0
rbits = 0
for char in val:
r = (r << 8) | char
rbits += 8
while rbits >= 5:
rbits -= 5
idx = r >> rbits
r &= (1 << rbits) - 1
result += charset[idx]
if rbits:
result += charset[r << (5 - rbits)]
return result
def decode(val, padded=True):
result = bytearray()
if not val:
return result
a = 0
abits = 0
for char in val:
a = (a << 5) | charset.index(char)
abits += 5
if abits >= 8:
abits -= 8
result.append(a >> abits)
a &= (1 << abits) -1
if not padded and abits:
result.append(a << (8 - abits))
return result