changeset 729:fc4749433229

https://gist.github.com/adyliu/4494223
author Jeff Hammel <k0scist@gmail.com>
date Wed, 10 Dec 2014 10:08:31 -0800
parents 6ba565f99696
children 9c2a18033128
files python/base_encode.py
diffstat 1 files changed, 43 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/python/base_encode.py	Wed Dec 10 10:08:31 2014 -0800
@@ -0,0 +1,43 @@
+#!/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
+ 
+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))) 
\ No newline at end of file