Mercurial > hg > config
annotate python/base_encode.py @ 917:372061cd29d7
web2 requires sudo for port 80
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Thu, 30 May 2024 18:59:32 -0700 |
parents | 9c2a18033128 |
children |
rev | line source |
---|---|
729
fc4749433229
https://gist.github.com/adyliu/4494223
Jeff Hammel <k0scist@gmail.com>
parents:
diff
changeset
|
1 #!/usr/bin/env python |
fc4749433229
https://gist.github.com/adyliu/4494223
Jeff Hammel <k0scist@gmail.com>
parents:
diff
changeset
|
2 #-*- coding:utf-8 -*- |
730 | 3 |
4 """ | |
5 arbitrary base encoding tools (convert number <=> string) | |
6 | |
7 modified from | |
8 https://gist.github.com/adyliu/4494223 | |
9 """ | |
10 | |
11 import argparse | |
12 import string | |
729
fc4749433229
https://gist.github.com/adyliu/4494223
Jeff Hammel <k0scist@gmail.com>
parents:
diff
changeset
|
13 import sys |
730 | 14 |
15 basedigits = string.digits + string.letters | |
16 | |
17 def decode(s, basedigits=basedigits): | |
18 | |
19 BASE = len(basedigits) | |
20 ret,mult = 0,1 | |
21 for c in reversed(s): | |
22 ret += mult*basedigits.index(c) | |
23 mult *= BASE | |
24 return ret | |
25 | |
26 def encode(num, basedigits=basedigits): | |
27 BASE = len(basedigits) | |
28 | |
29 if num < 0: | |
30 raise Exception("positive number "+num) | |
31 if num == 0: | |
32 return '0' | |
33 ret='' | |
34 while num: | |
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 | |
729
fc4749433229
https://gist.github.com/adyliu/4494223
Jeff Hammel <k0scist@gmail.com>
parents:
diff
changeset
|
66 if __name__ == '__main__': |
730 | 67 main() |