Skip to content

Instantly share code, notes, and snippets.

@toddlerya
Created March 31, 2019 11:24
Show Gist options
  • Save toddlerya/24ff96256ae4c8df2190a443d727d4ed to your computer and use it in GitHub Desktop.
Save toddlerya/24ff96256ae4c8df2190a443d727d4ed to your computer and use it in GitHub Desktop.
62进制与10进制转化,主要用于短URL生成解析
#!/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()
@white-shiro-bai
Copy link

作者你好。非常感谢您的代码。极大的帮助了我的工作。
您的代码被引用到了这里,分别在这两个文件上做了注明。

https://github.com/white-shiro-bai/ghost_sa/blob/master/README.md

https://github.com/white-shiro-bai/ghost_sa/blob/master/component/base62.py

在引用时,对您的第15行做了修改。以避免a和aa。因为进位,都会被转换成0的问题。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment