File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 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 ()
You can’t perform that action at this time.
0 commit comments