Advertisement
B1KMusic

b32c.py

Jan 18th, 2015
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. # Convert between "base-32" and ASCII
  2. # Written for python 3, but seems to work in python 2 as well
  3. from sys import argv
  4.  
  5. def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
  6.     # Original function courtesy of http://stackoverflow.com/a/2267721/1175714
  7.     # Most of the function is omitted; assuming x is non-negative real, as that's what an ASCII char is.
  8.     rets=''
  9.     while x>0:
  10.         x,idx = divmod(x,b)
  11.         rets = alphabet[idx] + rets
  12.     return rets
  13.  
  14. def b32_ascii(src):
  15.   a = src
  16.   a2 = "%x" % int(a,32)
  17.   b = ''
  18.   i = 0
  19.   while 1:
  20.     if i >= len(a2): break
  21.     b = b + chr(int(a2[i] + a2[i+1],16))
  22.     i += 2
  23.   print(b)
  24.  
  25.  
  26. def ascii_b32(src):
  27.   a = src
  28.   b = ''
  29.   for i in a:
  30.     b = b + int2base(ord(i),16)
  31.   print(int2base(int(b,16),32))
  32.  
  33. if len(argv) >= 2:
  34.   if argv[1] == "b":
  35.     b32_ascii(argv[2])
  36.   elif argv[1] == "a":
  37.     ascii_b32(argv[2])
  38. else:
  39.   print("=========================================================")
  40.   print("Usage:\t\tpython %s [option] [string]" % argv[0])
  41.   print("Options:")
  42.   print("  b:\t\tconvert base-32 string to ASCII")
  43.   print("  a:\t\tconvert ASCII string to base-32")
  44.   print("=========================================================")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement