comparison python/base_encode.py @ 730:9c2a18033128

flush out
author Jeff Hammel <k0scist@gmail.com>
date Wed, 10 Dec 2014 10:48:20 -0800
parents fc4749433229
children
comparison
equal deleted inserted replaced
729:fc4749433229 730:9c2a18033128
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*- 2 #-*- coding:utf-8 -*-
3 # Base62 tools (convert number <=> string) 3
4 # v1.0/20130109 4 """
5 # python 2.x/3.x supported 5 arbitrary base encoding tools (convert number <=> string)
6 # 6
7 #author: Ady Liu(imxylz@gmail.com) 7 modified from
8 #github: github.com/adyliu 8 https://gist.github.com/adyliu/4494223
9 9 """
10
11 import argparse
12 import string
10 import sys 13 import sys
11 14
12 basedigits='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 15 basedigits = string.digits + string.letters
13 BASE=len(basedigits) 16
14 17 def decode(s, basedigits=basedigits):
15 18
16 def decode(s): 19 BASE = len(basedigits)
17 ret,mult = 0,1 20 ret,mult = 0,1
18 for c in reversed(s): 21 for c in reversed(s):
19 ret += mult*basedigits.index(c) 22 ret += mult*basedigits.index(c)
20 mult *= BASE 23 mult *= BASE
21 return ret 24 return ret
22 25
23 def encode(num): 26 def encode(num, basedigits=basedigits):
24 if num <0: raise Exception("positive number "+num) 27 BASE = len(basedigits)
25 if num ==0: return '0' 28
26 ret='' 29 if num < 0:
27 while num != 0: 30 raise Exception("positive number "+num)
28 ret = (basedigits[num%BASE])+ret 31 if num == 0:
29 num = int(num/BASE) 32 return '0'
30 return ret 33 ret=''
31 34 while num:
32 35 ret = (basedigits[num%BASE])+ret
36 num = int(num/BASE)
37 return ret
38
39
40 def main(args=sys.argv[1:]):
41
42 parser = argparse.ArgumentParser(description=__doc__)
43 parser.add_argument('num', nargs='+',
44 help="num")
45 parser.add_argument('-b', '--base', dest='base',
46 type=int, default=32,
47 help="base to use [DEFAULT: %(default)s]")
48 parser.add_argument('-c', '--chars', '--base-digits', dest='basedigits',
49 default=globals()['basedigits'],
50 help="base digits [DEFAULT: %(default)s]")
51 options = parser.parse_args(args)
52
53 # determine base digits
54 basedigits = options.basedigits[:options.base]
55 base = len(basedigits)
56
57 for num in options.num:
58
59 try:
60 num = int(num)
61 encoded = encode(num, basedigits)
62 print ('ENCODE base {}: {}->{} [{}]'.format(base, num, encoded, len(encoded)))
63 except ValueError:
64 print ('%*s %s %s' % ('DECODE', num, decode(num)))
65
33 if __name__ == '__main__': 66 if __name__ == '__main__':
34 if len(sys.argv) < 2: 67 main()
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)))