Matt23

Converting numbers systems

Nov 30th, 2015
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. def convertNumber(base, n, to):
  2.     digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3.     decimal = 0
  4.  
  5.     if base > 36 or to > 36:
  6.         print("Numbers based on systems grather than 36 are not supported")
  7.         return
  8.  
  9.     for exponent, i in enumerate(str(n)[::-1]):
  10.         if digits.index(i) >= base:
  11.             print("Value {0} is not written in {1} based system, conversion impossible").format(n, base)
  12.             return
  13.         decimal += digits.index(i) * base ** exponent
  14.  
  15.     result = ""
  16.     while decimal >= 1:
  17.         result += digits[decimal % to]
  18.         decimal /= to
  19.     print result[::-1]
  20.  
  21. convertNumber(16, "DEAD", 10)
  22. convertNumber(10, 57005, 16)
Advertisement
Add Comment
Please, Sign In to add comment