Advertisement
Guest User

Untitled

a guest
Jan 14th, 2009
3,518
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. BASE2 = "01"
  2. BASE10 = "0123456789"
  3. BASE16 = "0123456789ABCDEF"
  4. BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"
  5.  
  6. def baseconvert(number,fromdigits,todigits):
  7.     """ converts a "number" between two bases of arbitrary digits
  8.  
  9.    The input number is assumed to be a string of digits from the
  10.    fromdigits string (which is in order of smallest to largest
  11.    digit). The return value is a string of elements from todigits
  12.    (ordered in the same way). The input and output bases are
  13.    determined from the lengths of the digit strings. Negative
  14.    signs are passed through.
  15.  
  16.    decimal to binary
  17.    >>> baseconvert(555,BASE10,BASE2)
  18.    '1000101011'
  19.  
  20.    binary to decimal
  21.    >>> baseconvert('1000101011',BASE2,BASE10)
  22.    '555'
  23.  
  24.    integer interpreted as binary and converted to decimal (!)
  25.    >>> baseconvert(1000101011,BASE2,BASE10)
  26.    '555'
  27.  
  28.    base10 to base4
  29.    >>> baseconvert(99,BASE10,"0123")
  30.    '1203'
  31.  
  32.    base4 to base5 (with alphabetic digits)
  33.    >>> baseconvert(1203,"0123","abcde")
  34.    'dee'
  35.  
  36.    base5, alpha digits back to base 10
  37.    >>> baseconvert('dee',"abcde",BASE10)
  38.    '99'
  39.  
  40.    decimal to a base that uses A-Z0-9a-z for its digits
  41.    >>> baseconvert(257938572394L,BASE10,BASE62)
  42.    'E78Lxik'
  43.  
  44.    ..convert back
  45.    >>> baseconvert('E78Lxik',BASE62,BASE10)
  46.    '257938572394'
  47.  
  48.    binary to a base with words for digits (the function cannot convert this back)
  49.    >>> baseconvert('1101',BASE2,('Zero','One'))
  50.    'OneOneZeroOne'
  51.  
  52.    """
  53.  
  54.     if str(number)[0]=='-':
  55.         number = str(number)[1:]
  56.         neg=1
  57.     else:
  58.         neg=0
  59.  
  60.     # make an integer out of the number
  61.     x=0
  62.     for digit in str(number):
  63.        x = x*len(fromdigits) + fromdigits.index(digit)
  64.    
  65.     # create the result in base 'len(todigits)'
  66.     if x == 0:
  67.         res = todigits[0]
  68.     else:
  69.         res=""
  70.         while x>0:
  71.             digit = x % len(todigits)
  72.             res = todigits[digit] + res
  73.             x = int(x / len(todigits))
  74.         if neg:
  75.             res = "-"+res
  76.  
  77.     return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement