Created
March 31, 2019 11:24
-
-
Save toddlerya/ce094ea66c4da89acaf58dbe688de099 to your computer and use it in GitHub Desktop.
62进制与10进制转化,主要用于短URL生成解析
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# encoding: utf-8 | |
# author: toddlerya | |
# date: 2019/03/31 | |
import string | |
class Base62(object): | |
""" | |
基于abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789共计62个ascii字符 | |
构建62进制编码, 实现正整形十进制数据字符编码和解码 | |
""" | |
def __init__(self): | |
self.BASE_STR = string.ascii_letters + string.digits | |
self.BASE = len(self.BASE_STR) | |
def __10to62(self, digit, value=None): | |
# 小心value参数的默认传参数陷阱 | |
# 不应写为value=[], 这将导致只有一次初始化, 每次调用列表的值都会累加 | |
# 应该声明为None, 只有为None才进行初始化, 这样能保持每次调用都会初始化此参数 | |
# https://pythonguidecn.readthedocs.io/zh/latest/writing/gotchas.html | |
if value is None: | |
value = list() | |
rem = int(digit % self.BASE) | |
value.append(self.BASE_STR[rem]) | |
div = int(digit / self.BASE) | |
if div > 0: | |
value = self.__10to62(div, value) | |
return value | |
def __62to10(self, str_value): | |
value_list = list(str_value) | |
value_list.reverse() | |
temp_list = [self.BASE_STR.index(ele) * (62 ** n) for n, ele in enumerate(value_list)] | |
return sum(temp_list) | |
def encode_10to62(self, digit: int) -> str: | |
""" | |
10进制转为62进制 | |
""" | |
value = self.__10to62(digit) | |
value.reverse() | |
value = ''.join(value) | |
return value | |
def decode_62to10(self, str62: str) -> int: | |
""" | |
62进制转为10进制 | |
""" | |
return self.__62to10(str62) | |
def main(): | |
code = Base62() | |
print(code.encode_10to62(0)) | |
print(code.encode_10to62(10)) | |
print(code.encode_10to62(61)) | |
print(code.encode_10to62(62)) | |
print(code.encode_10to62(122262)) | |
print('==' * 20) | |
print(code.decode_62to10('a')) | |
print(code.decode_62to10('k')) | |
print(code.decode_62to10('9')) | |
print(code.decode_62to10('ab')) | |
print(code.decode_62to10('ba')) | |
print(code.decode_62to10('FX8')) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment