Converts a decimal to it's hexadecimal equivalent
Python, 6 lines
1 2 3 4 5 6
def main(): user_input=raw_input("Please enter a number\n") val = int(user_input) print "The decimal %d is %X in hexadecimal.\n"%(val, val) main()
This is Akira Fora's rewrite
Akira, in the author's defense your example doesn't teach you to understand hexadecimal. Still, OMG is right!
Coincidentally works with any base. Just specify the digits and you're done.
"digits" can be a string, strings can be accessed as arrays of characters.
Integer division has an operator ("//"), but even better is to use the built-in function divmod.
It is traditional to write numbers from left to right, even in hex, so reverse the output digits.
In the common case of the base being a power of 2, depending on how numbers are represented, it is faster to use binary AND for remainder and a right shift for division.
decNumber = input("Number in decimal system: ") numBase = input("Base of number system, to which number shall be transformed (<= 24): ") if numBase > 10: moreThanDec = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L', 'M', 'N']
listOfRemainders =  while(decNumber > 0): (decNumber,remainder) = divmod(decNumber, numBase) if numBase > 10: remainderAlpha = moreThanDec[remainder] listOfRemainders.append(remainderAlpha) else: listOfRemainders.append(str(remainder))
listOfRemainders.reverse() for i in listOfRemainders: print i,
A generalisation: (sorry for the missing formatting before)