Skip to content

Instantly share code, notes, and snippets.

@seozed
Last active January 10, 2020 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seozed/4f0c28a1949e24f223ca3d220b0343b1 to your computer and use it in GitHub Desktop.
Save seozed/4f0c28a1949e24f223ca3d220b0343b1 to your computer and use it in GitHub Desktop.
62进制转换
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62_encode(num, alphabet=ALPHABET):
"""Encode a number in Base X
`num`: The number to encode
`alphabet`: The alphabet to use for encoding
"""
if (num == 0):
return alphabet[0]
arr = []
base = len(alphabet)
while num:
rem = num % base
num = num // base
arr.append(alphabet[rem])
arr.reverse()
return ''.join(arr)
def base62_decode(string, alphabet=ALPHABET):
"""Decode a Base X encoded string into the number
Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for encoding
"""
base = len(alphabet)
strlen = len(string)
num = 0
idx = 0
for char in string:
power = (strlen - (idx + 1))
num += alphabet.index(char) * (base ** power)
idx += 1
return num
if __name__ == '__main__':
key = base62_encode(9999)
print(key)
number = base62_decode(key)
print(number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment