Skip to content

Instantly share code, notes, and snippets.

@adyliu
Created January 9, 2013 15:55
Show Gist options
  • Save adyliu/4494223 to your computer and use it in GitHub Desktop.
Save adyliu/4494223 to your computer and use it in GitHub Desktop.
Base62 encode/decode tools (convert number to string)
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Base62 tools (convert number <=> string)
# v1.0/20130109
# python 2.x/3.x supported
#
#author: Ady Liu([email protected])
#github: github.com/adyliu
import sys
basedigits='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
BASE=len(basedigits)
def decode(s):
ret,mult = 0,1
for c in reversed(s):
ret += mult*basedigits.index(c)
mult *= BASE
return ret
def encode(num):
if num <0: raise Exception("positive number "+num)
if num ==0: return '0'
ret=''
while num != 0:
ret = (basedigits[num%BASE])+ret
num = int(num/BASE)
return ret
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: base62.py <num>...")
sys.exit(1)
width = max(len(x) for x in sys.argv[1:])
for argv in sys.argv[1:]:
try:
num = int(argv)
print('%*s %s %s' % (width,argv,'ENCODE',encode(num)))
except ValueError:
print('%*s %s %s' % (width,argv,'DECODE',decode(argv)))
adylab:bin adyliu$ python base62.py 16075652386131968 1bCQSgeUyk
16075652386131968 ENCODE 1bCQSgeUyk
1bCQSgeUyk DECODE 16075652386131968
adylab:bin adyliu$ python3 base62.py 16075652386131968 1bCQSgeUyk
16075652386131968 ENCODE 1bCQSgeUyk
1bCQSgeUyk DECODE 16075652386131968
@mrffrm1234
Copy link

Awesome mate!

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