In this example I used doctest to validate the results.
def int2hex(n):
'''
:param n: int
:return: str
>>> int2hex(10)
'A'
>>> int2hex(15)
'F'
>>> int2hex(32)
'20'
>>> int2hex(255)
'FF'
>>> int2hex(65535)
'FFFF'
'''
x16 = '0 1 2 3 4 5 6 7 8 9 a b c d e f'.upper().split()
result = []
while n > 0:
result.append(x16[(n % 16)])
n = n // 16
result.reverse()
return ''.join(result)
if __name__ == '__main__':
import doctest
doctest.testmod()
print(int2hex(64202))
The excerpt:
>>> int2hex(10)
'A'
Refer to doctest calls, where the first line is the method call and the second is the expected result.
On line:
x16 = '0 1 2 3 4 5 6 7 8 9 a b c d e f'.upper().split()
I create a high-box list with hexadecimal values.
In the excerpt:
while n > 0:
result.append(x16[(n % 16)])
n = n // 16
I decompose base number 10 to base 16, however it is stored in reverse.
On line:
result.reverse()
I inverted the values stored in the list.
and finally in the line:
return ''.join(result)
I convert the list to string and return it as a response.
How to run the excerpt:
print(int2hex(64202))
results in 'FACA'
If it is necessary to enter the values in the format string, you can add a casting and also treatment of exceptions.
Complete example:
def int2hex(n):
'''
:param n: int
:return: str
>>> int2hex(10)
'A'
>>> int2hex(15)
'F'
>>> int2hex(32)
'20'
>>> int2hex(255)
'FF'
>>> int2hex(65535)
'FFFF'
'''
x16 = '0 1 2 3 4 5 6 7 8 9 a b c d e f'.upper().split()
result = []
try:
n = int(n)
while n > 0:
result.append(x16[(n % 16)])
n = n // 16
result.reverse()
except ValueError as e:
return ('Erro: %s' %e)
except:
raise
else:
return ''.join(result)
if __name__ == '__main__':
import doctest
doctest.testmod()
print(int2hex(64202))
print(int2hex('20'))
print(int2hex('a'))
print(int2hex('15'))