If you want to handle larger numbers, you must add a while loop which runs as long as the number is not zero. Here is a way to do it
HEX_DIGITS = "0123456789ABCDEF"
def hex_digit(n):
"""Compute the hexadecimal digit for a number n in [0, 16[.
>>> hex_digit(7)
'7'
>>> hex_digit(12)
'C'
>>> hex_digit(20)
Traceback (most recent call last):
...
"""
assert 0 <= n < 16
return HEX_DIGITS[n]
def dec_to_hex(n):
"""Compute the hexadecimal representation of a non negative integer"""
assert n >= 0
if n == 0:
return '0'
result = ''
while n:
n, rest = divmod(n, 16)
result = hex_digit(rest) + result
return result
Notice that the standard library contains a function hex() which does exactly this. Try hex(n)[2:].upper().
For a better style, use documentation strings in your functions, and also use assert statements to check things that look obvious when you're writing the code but which may fail when the code is used (like assert n >= 0).
Gribouillis
Posting Maven
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11