84 lines
No EOL
1.6 KiB
Python
84 lines
No EOL
1.6 KiB
Python
class NumberException(Exception):
|
|
pass
|
|
|
|
class NumericSystemException(Exception):
|
|
pass
|
|
|
|
class Zahlensystem:
|
|
chars = map(str, range(0,10)) + map(chr, range(ord('A'), ord('F')+1))
|
|
def __init__(self, basis):
|
|
self.basis = int(basis)
|
|
if self.basis > 16 or self.basis < 2:
|
|
raise NumberException("Numeric system %d is invalid" % (self.basis,))
|
|
|
|
def fromNum(self, num):
|
|
if type(num) != str:
|
|
num = str(num)
|
|
|
|
if "." in num:
|
|
pre, post = num.split(".",2)
|
|
else:
|
|
pre = num
|
|
post = ""
|
|
|
|
value = 0
|
|
|
|
for i,c in enumerate(pre):
|
|
e = (len(pre)-i-1)
|
|
try:
|
|
f = self.chars[:self.basis].index(c.upper())
|
|
except ValueError:
|
|
raise NumberException("%d isn't a %d based number" % (f,self.basis))
|
|
|
|
value += f * self.basis**e
|
|
|
|
for i,c in enumerate(post):
|
|
e = (-i-1)
|
|
try:
|
|
f = self.chars[:self.basis].index(c.upper())
|
|
except ValueError:
|
|
raise NumberException("%d isn't a %d based number" % (f,self.basis))
|
|
|
|
value += f * self.basis**e
|
|
|
|
return value
|
|
|
|
def toNum(self, num):
|
|
num = float(num)
|
|
|
|
if num < 0:
|
|
neg = True
|
|
num = -num
|
|
else:
|
|
neg = False
|
|
|
|
pre, post = divmod(num, 1)
|
|
|
|
v = ""
|
|
|
|
if pre != 0:
|
|
n = pre
|
|
while n != 0:
|
|
n, r = divmod(n, self.basis)
|
|
v = self.chars[int(r)] + v
|
|
else:
|
|
v = "0"
|
|
|
|
if post != 0:
|
|
v = v + "."
|
|
n = post
|
|
while n != 0:
|
|
r, n = divmod(n * self.basis, 1)
|
|
v = v + self.chars[int(r)]
|
|
|
|
if neg:
|
|
v = "-" + v
|
|
|
|
return v
|
|
|
|
if __name__ == '__main__':
|
|
num = raw_input("Num> ")
|
|
fr = int(raw_input("From> "))
|
|
to = int(raw_input("To> "))
|
|
|
|
print Zahlensystem(to).toNum(Zahlensystem(fr).fromNum(num)) |