How to Convert a Hexadecimal Value to Decimal in Python?

Estimated read time 1 min read

To convert a hexadecimal value to decimal in Python, you can use the int() function with the base argument set to 16. Here’s an example:

# Define a hexadecimal value
hex_value = '1A'

# Convert hexadecimal value to decimal
decimal = int(hex_value, 16)

# Print the decimal value
print(decimal)

In this example, we have a hexadecimal value '1A'.

To convert the hexadecimal value to decimal, we use the int() function and pass the hexadecimal value as the first argument. We also specify the base argument as 16 to indicate that the string should be interpreted as a hexadecimal number.

The output will be:

26

In this case, the hexadecimal value '1A' is converted to the corresponding decimal value, which is 26.

Note that the int() function can handle hexadecimal values of any length. Ensure that the hexadecimal value only contains valid hexadecimal digits (0-9, A-F or a-f) to avoid raising a ValueError.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply