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
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap