changeset 730:9c2a18033128

flush out
author Jeff Hammel <k0scist@gmail.com>
date Wed, 10 Dec 2014 10:48:20 -0800
parents fc4749433229
children e56610c5ece2
files python/base_encode.py
diffstat 1 files changed, 63 insertions(+), 39 deletions(-) [+]
line wrap: on
line diff
--- a/python/base_encode.py	Wed Dec 10 10:08:31 2014 -0800
+++ b/python/base_encode.py	Wed Dec 10 10:48:20 2014 -0800
@@ -1,43 +1,67 @@
 #!/usr/bin/env python
 #-*- coding:utf-8 -*-
-# Base62 tools (convert number <=> string)
-# v1.0/20130109
-# python 2.x/3.x supported
-#
-#author: Ady Liu(imxylz@gmail.com)
-#github: github.com/adyliu
- 
+
+"""
+arbitrary base encoding tools (convert number <=> string)
+
+modified from
+https://gist.github.com/adyliu/4494223
+"""
+
+import argparse
+import string
 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
- 
- 
+
+basedigits = string.digits + string.letters
+
+def decode(s, basedigits=basedigits):
+
+    BASE = len(basedigits)
+    ret,mult = 0,1
+    for c in reversed(s):
+        ret += mult*basedigits.index(c)
+        mult *= BASE
+    return ret
+
+def encode(num, basedigits=basedigits):
+    BASE = len(basedigits)
+
+    if num < 0:
+        raise Exception("positive number "+num)
+    if num == 0:
+        return '0'
+    ret=''
+    while num:
+        ret = (basedigits[num%BASE])+ret
+        num = int(num/BASE)
+    return ret
+
+
+def main(args=sys.argv[1:]):
+
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument('num', nargs='+',
+                        help="num")
+    parser.add_argument('-b', '--base', dest='base',
+                        type=int, default=32,
+                        help="base to use [DEFAULT: %(default)s]")
+    parser.add_argument('-c', '--chars', '--base-digits', dest='basedigits',
+                        default=globals()['basedigits'],
+                        help="base digits [DEFAULT: %(default)s]")
+    options = parser.parse_args(args)
+
+    # determine base digits
+    basedigits = options.basedigits[:options.base]
+    base = len(basedigits)
+
+    for num in options.num:
+
+        try:
+            num = int(num)
+            encoded = encode(num, basedigits)
+            print ('ENCODE base {}: {}->{} [{}]'.format(base, num, encoded, len(encoded)))
+        except ValueError:
+            print ('%*s %s %s' % ('DECODE', num, decode(num)))
+
 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))) 
\ No newline at end of file
+    main()