Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- def considerHex(letter):
- if letter == "A" or letter == "a":
- return 10
- if letter == "B" or letter == "b":
- return 11
- if letter == "C" or letter == "c":
- return 12
- if letter == "D" or letter == "d":
- return 13
- if letter == "E" or letter == "e":
- return 14
- if letter == "F" or letter == "f":
- return 15
- else:
- return int(letter)
- def main():
- # retrieve an input from the user
- # if type isnt number output error and get input again
- # if type is number then store it and retrieve input again for the base of the number supplied
- # store the number for the base of the number supplied
- # ask the user for the base of the desired output nuymber
- # calculate the conversion and return it
- originalNumber = input("Please input a number: ")
- originalBase = int(input("Please input the base of your number in numerical form: "))
- outputBase = int(input("Please input the base of the desired conversion: "))
- baseTen = 0
- maxExponent = 30
- outputNumber = 0
- for index, digit in enumerate(originalNumber):
- # add consideration for bases higher than 10
- digit = considerHex(digit)
- currentPlace = (len(originalNumber) - index - 1)
- baseTen += digit * (originalBase ** (len(originalNumber) - index - 1))
- print("your number in base 10 is %s" % baseTen)
- # now convert to output base
- while baseTen >= 0 and maxExponent >= 0:
- currentDigit = baseTen / (outputBase ** maxExponent)
- if 1 <= currentDigit < baseTen:
- multiplier = math.floor((baseTen / (outputBase ** maxExponent)))
- if multiplier == 0:
- multiplier = 1
- outputNumber += multiplier * (10 ** maxExponent)
- baseTen -= multiplier * (outputBase ** maxExponent)
- maxExponent -= 1
- # add the last trailing remainder of baseTen
- outputNumber += baseTen
- baseTen -= baseTen
- print("your number in base %s is %s" % (outputBase, outputNumber))
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement