BASE2 = "01"BASE10 = "0123456789"BASE16 = "0123456789ABCDEF"BASE62 = "ABCD - Pastebin.com (original) (raw)

Guest User

Untitled

a guest

Jan 14th, 2009

3,690

0

Never

Not a member of Pastebin yet? Sign Up, it unlocks many cool features!

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