Site icon codippa

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.

Hit the clap if you found this article useful.

Exit mobile version