#
# This program reads in a base (between 2 and 36 inclusive)
# and a number, and converts the number in that base to decimal
# It then asks the user for an output base, and converts that
# number to that base
#
# Matt Bishop ECS 36A, Winter 2019
#
# digits for base 36
#
cvtdigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#
# convert number to decimal
#
def baseto10(ibase, num):
# assume no error and initialize the accumulator
err = False
decnum = 0
# now loop, processing num
for i in num:
# convert the dgit to an integer
# we do it this way because the
# digita and letters (for > 9) are
# not contiguous
digval = cvtdigits.find(i)
# oops ... error; say so but keep going
# so you can identify all bad digits
if digval == -1 or digval >= ibase:
print("Invalid digit:", i)
err = True
continue
# good digit ... add it in
decnum = digval + decnum * ibase
#
# return what you got and whether there was an error
#
return err, decnum
#
# convert number from decimal
#
def basefrom10(obase, num):
# starting string; the digita accumulate here
out = ""
# loop until you're done with the number
while num > 0:
# get the integer value of the last digit
digval = num % obase
# put it at the *front* of the current number
out = cvtdigits[digval] + out
# move on to the next digit
num = num // obase
# return the string
return out
#
# read in a base
# it *must* be an integer between 2 and 36 inclusive
# as those are the bases for which we have digits
#
def readbase(prompt):
# we catch everything here
try:
# get the base
base = int(input(prompt))
except (EOFerror, KeyboardInterrupt):
# all done!
return -1
except Exception as msg:
# unknown exception -- say what it is and give up
print(msg)
return -1
#
# we have input as an integer; be sure the integer is valid
#
if base < 2 or base > 36:
print("Invalid base"+str(base)+"; must be between 2 and 36 inclusive")
return -1
# it is -- return it
return base
def main():
#
# read in the number, removing blanks
#
num = input("Number to be converted: ")
num = num.strip()
#
# read the input base
#
inbase = readbase("Input base: ")
if inbase == -1:
return
#
# convert it to base 10
# errot is True if there was a problem; if so, quit
#
error, decnum = baseto10(inbase, num)
if not error:
#
# okay, it's good -- print out the number
#
#print(num, "in base", inbase, "is", decnum, "in decimal")
#
# get the output base; EOF ends it all
#
outbase = readbase("Output base (EOF to quit): ")
if outbase != -1:
print(basefrom10(outbase, decnum))
main()