Skip to content

Commit d81c5c8

Browse files
Add Base62 encoding and decoding algorithm.
1 parent 8106aea commit d81c5c8

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

ciphers/base62.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import string
2+
3+
CHARSET = string.digits + string.ascii_lowercase + string.ascii_uppercase
4+
5+
def base62_encode(num: int) -> str:
6+
"""
7+
Encodes a positive integer into a base62 string.
8+
>>> base62_encode(0)
9+
'0'
10+
>>> base62_encode(123)
11+
'1z'
12+
>>> base62_encode(1000000)
13+
'4C92'
14+
"""
15+
if num == 0:
16+
return CHARSET[0]
17+
18+
arr = []
19+
base = len(CHARSET)
20+
while num:
21+
num, rem = divmod(num, base)
22+
arr.append(CHARSET[rem])
23+
arr.reverse()
24+
return "".join(arr)
25+
26+
def base62_decode(string_val: str) -> int:
27+
"""
28+
Decodes a base62 string into a positive integer.
29+
>>> base62_decode('0')
30+
0
31+
>>> base62_decode('1z')
32+
123
33+
>>> base62_decode('4C92')
34+
1000000
35+
"""
36+
base = len(CHARSET)
37+
strlen = len(string_val)
38+
num = 0
39+
40+
idx = 0
41+
for char in string_val:
42+
power = strlen - (idx + 1)
43+
num += CHARSET.index(char) * (base**power)
44+
idx += 1
45+
return num
46+
47+
if __name__ == "__main__":
48+
import doctest
49+
doctest.testmod()

0 commit comments

Comments
 (0)