In this example below 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 in the first line is the method call and the second is the expected result.
On the 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 stretch:
while n > 0:
result.append(x16[(n % 16)])
n = n // 16
I decompose base number 10 to base number 16, however it is stored in reverse.
On the line:
result.reverse()
I invert the values stored in the list.
and last in line:
return ''.join(result)
convert the list into string and return as response.
How to execute the excerpt:
print(int2hex(64202))
presents as a result 'KNIFE'
If it is necessary to input the values in the string format, one can add a casting and also exception handling.
Full 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'))
I don’t quite understand, please go straight to the problem.
– Francisco