Advertisement
Guest User

base_decode and base_encode

a guest
Aug 12th, 2014
563
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.63 KB | None | 0 0
  1. from string import digits, ascii_uppercase, ascii_lowercase
  2.  
  3.  
  4. # every character except the dash (-) is allowed as a digit
  5. DIGITS = tuple(digits + ascii_uppercase + ascii_lowercase)
  6. DIGITS_TO_DECIMAL = dict((c, i) for i, c in enumerate(DIGITS))
  7. BASE = len(DIGITS)
  8.  
  9.  
  10. def base_decode(string, base=BASE, digits_to_decimal=DIGITS_TO_DECIMAL):
  11.     """
  12.    Decodes a number with a custom base (in form of a string) to a decimal.
  13.  
  14.    By default the digits are 0-9, A-Z, a-z and thus the base is 62.
  15.    You need to supply the base and a dictionary that maps every digit to a
  16.    decimal.
  17.  
  18.    >>> base_decode('0')
  19.    0
  20.    >>> base_decode('z')
  21.    61
  22.    >>> base_decode('10')
  23.    62
  24.    >>> base_decode('-y')
  25.    -60
  26.    """
  27.     factor = 1
  28.     if string.startswith("-"):
  29.         string = string[1:]
  30.         factor = -1
  31.  
  32.     number = 0
  33.     for c in string:
  34.         number = number * base + digits_to_decimal[c]
  35.  
  36.     return factor * number
  37.  
  38.  
  39. def base_encode(number, base=BASE, digits=DIGITS):
  40.     """
  41.    Encodes a decimal to a number with a custom base in form of a string.
  42.  
  43.    By default the digits are 0-9, A-Z, a-z and thus the base is 62.
  44.    You need to supply the base and the digits.
  45.  
  46.    >>> base_encode(0)
  47.    '0'
  48.    >>> base_encode(61)
  49.    'z'
  50.    >>> base_encode(62)
  51.    '10'
  52.    >>> base_encode(-60)
  53.    '-y'
  54.    """
  55.     if not number:
  56.         return digits[0]
  57.  
  58.     prefix = ""
  59.     if number < 0:
  60.         prefix = "-"
  61.         number = abs(number)
  62.  
  63.     string = ""
  64.     while number:
  65.         number, rem = divmod(number, base)
  66.         string = digits[rem] + string
  67.  
  68.     return prefix + string
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement