comparison python/base_encode.py @ 729:fc4749433229

https://gist.github.com/adyliu/4494223
author Jeff Hammel <k0scist@gmail.com>
date Wed, 10 Dec 2014 10:08:31 -0800
parents
children 9c2a18033128
comparison
equal deleted inserted replaced
728:6ba565f99696 729:fc4749433229
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 # Base62 tools (convert number <=> string)
4 # v1.0/20130109
5 # python 2.x/3.x supported
6 #
7 #author: Ady Liu(imxylz@gmail.com)
8 #github: github.com/adyliu
9
10 import sys
11
12 basedigits='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
13 BASE=len(basedigits)
14
15
16 def decode(s):
17 ret,mult = 0,1
18 for c in reversed(s):
19 ret += mult*basedigits.index(c)
20 mult *= BASE
21 return ret
22
23 def encode(num):
24 if num <0: raise Exception("positive number "+num)
25 if num ==0: return '0'
26 ret=''
27 while num != 0:
28 ret = (basedigits[num%BASE])+ret
29 num = int(num/BASE)
30 return ret
31
32
33 if __name__ == '__main__':
34 if len(sys.argv) < 2:
35 print("Usage: base62.py <num>...")
36 sys.exit(1)
37 width = max(len(x) for x in sys.argv[1:])
38 for argv in sys.argv[1:]:
39 try:
40 num = int(argv)
41 print('%*s %s %s' % (width,argv,'ENCODE',encode(num)))
42 except ValueError:
43 print('%*s %s %s' % (width,argv,'DECODE',decode(argv)))