Skip to content

Instantly share code, notes, and snippets.

@debbbbie
Last active August 26, 2022 12:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debbbbie/8450336 to your computer and use it in GitHub Desktop.
Save debbbbie/8450336 to your computer and use it in GitHub Desktop.
[python]16-62进制互转
#coding=gbk
#
#62进制,特别合于月、日、时、分、秒的压缩进储
#
digit62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
#整数转化为62进制字符串
#入口:
# x : 整数
#返回: 字符串
def int_to_str62( x ):
try:
x=int(x)
except:
x=0
if x<0:
x=-x
if x==0:
return "0"
s=""
while x>62:
x1= x % 62
s = digit62[x1]+s
x = x // 62
if x>0:
s = digit62[x]+s
return s
#62进制字符串转化为整数
#入口:
# s : 62进制字符串
#返回: 整数
def str62_to_int( s ):
x = 0
s = str(s).strip()
if s=="":
return x
for y in s:
k = digit62.find(y)
if k>=0:
x=x*62+k
return x
x = 58
s = int_to_str62(x)
y = str62_to_int( s)
print( x , s , y)
# http://hi.baidu.com/jxq61/item/62b54ad5b8121fcf1b72b4b6
@cheneyveron
Copy link

应该是while x > 61,否则当x==62时while不会进,下面的if进去后导致digit62[x]下标溢出

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