Decimal To Hexadecimal Conversion In Python
Published on July 31 2023
In this tutorial you will see how to convert decimal numbers into hexadecimal numbers using logical implementation. Also, we will use built in methods and understand each line in detail.
Source code
decimal_value = int(input("Enter any integer value:"))
# Method - 1 - Using custom logic implementation
def decimal_to_hexa(num):
conversion_table = {
0: '0', 1: '1', 2: '2', 3: '3',
4: '4', 5: '5', 6: '6', 7: '7',
8: '8', 9: '9', 10: 'A', 11: 'B',
12: 'C', 13: 'D', 14: 'E', 15: 'F'
}
hexa_value = ""
while num > 0:
remainder = num % 16
hexa_value = hexa_value + conversion_table[remainder]
# hexa_value = conversion_table[remainder] + hexa_value
# above line can be used to avoid reversing of final output
num = num // 16
# return hexa_value
return hexa_value[::-1]
output = decimal_to_hexa(decimal_value)
print('Hexa value:', output)
# Method - 2 - Using Built In Method - hex()
output = hex(decimal_value)
print(output[2:])
# Method - 3 - Using Built In Method - format()
output = format(decimal_value, 'x')
print(output)
Next Tutorial
- Decimal To Binary Conversion In Python
- Binary To Decimal Conversion In Python
- Decimal To Hexadecimal Conversion In Python
- Decimal To Octal Conversion In Python
- Octal To Decimal Conversion In Python
- Hexadecimal To Decimal In Python