36: Python Program Convert Hex String to Integer

Question: Write Python Program to Convert Hex String to Integer.


Solution

input_hex_string = input("Enter a hexadecimal number: ").strip()

try:
    decimal_value = int(input_hex_string, 16)
    print(f"Decimal: {decimal_value}")
    print(f"Hexadecimal: {hex(decimal_value)[2:].upper()}")
except ValueError:
    print("Error! Invalid hexadecimal input.")

Output:

Enter a hexadecimal number: 2E
Decimal: 46
Hexadecimal: 2E

Enter a hexadecimal number: FFFFFF
Decimal: 16777215
Hexadecimal: FFFFFF

Enter a hexadecimal number: CAFEBABE
Decimal: 3405691582
Hexadecimal: CAFEBABE
Python Program Hex to Int Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!