How to convert hex to decimal in python

Converting a hexadecimal string to decimal or integer format is often required in programming applications. A common requirement is to convert IP addresses in hex to their decimal form.
This article will explain the conversion of a string from hex to decimal in python.

Hex to decimal conversion
Python library provides an int function which can be used to convert a hex value into decimal format. It accepts 2 arguments.

  1. First is the number that needs to be converted. It may be supplied as an integer or a string.
  2. Second is the base of the first argument.

int returns an integer representation(or base 10 equivalent) of the first argument. In other words, it converts the value supplied to it in decimal(base 10) format.

If int is called with 2 arguments, then the first argument must be a string.

Thus, if you provide a hexadecimal value to int, it will convert it into decimal. Example,

# hex string
num_hex = '0F'  
# convert hex to decimal
num_dec = int(num_hex, 16)
print('Value in hex:', num_hex)
print('Value in decimal:', num_dec)

Following is the output of above program

Value in hex: 0F
Value in decimal: 15

You can also use int function to convert a number in binary to decimal or an octal value to decimal. For binary to decimal, the second argument to int will be 2 and for octal, it will be 8.
Gotchas
Remember below pointers while using this method to convert hex to decimal.

  • If the base is not supplied to int, it will consider the number to be in decimal(base 10) format since default value of base is 10.
    Thus, if you omit the base and modify the int(num_hex, 16) to int(num_hex), then you will get an error.

    ValueError: invalid literal for int() with base 10: ‘0F’

  • If base is supplied, then the first argument should be a string. Trying to use a number will again raise an error.

    TypeError: int() can’t convert non-string with explicit base

Hit the clap if you found this article useful.

Leave a Reply