Python | Convert Hex to Decimal

Hexadecimal contains a digit from “0” to “9” that is followed by letters “A” to “F”, the hex values are operated by base “16”. While decimal values have bases of “10” that contain digits from “0” to “9”. Python supports the conversion of elements through different functions and modules. To convert the hexadecimal value into a decimal value, various methods are used in Python.

This write-up will provide a comprehensive guide on converting hex to decimal values in Python with multiple examples. The contents followed in the article are listed below:

So, let’s begin this guide!

How to Convert Hex to Decimal in Python?

To convert hex to decimal in Python, the inbuilt “int()” and “literal_eval()” function of the “ast” library is used. The “while” loop and “dictionary” can also convert any hexadecimal value into decimal.

How to install Kali Linux in Window...

Now let’s see each method with detailed working of code:

Method 1: Using int() Function

In the below example, the “int()” function is used to convert the hexadecimal value into a decimal value.

Code:

# create hexadecimal string
hex_value = '0B' 

# using int() Function
dec_value = int(hex_value, 16)

print('Hexadecimal Value:', hex_value)
print('Decimal Value:', dec_value)

In the above code:

  • The hexadecimal value is initialized as a string and stored in a variable named “hex_value”.
  • The “int()” function takes the hexadecimal variable as a first parameter and the integer value “16” as a second parameter. As we know, hexadecimal number systems are represented by base “16”.
  • The “int()” function converts the hexadecimal value to a decimal value.

Output:

The above output successfully converted hexadecimal value into decimal value.

Method 2: Using literal_eval()

In the example given below, the “literal_eval()” function of the “ast” module is used to predict the base and convert the hexadecimal value into decimal.

Code:

from ast import literal_eval

# create hexadecimal string
hex_value = '0xC'

# using ast.literal_eval()
output = literal_eval(hex_value)

print("Hexadecimal Value : ", hex_value)
print("Decimal Value : ", output)

In the above code:

  • The “literal_eval()” function of the “ast” module is imported at the start of the program.
  • The hexadecimal value is initialized to a variable named “hex_value”.
  • The “literal_eval()” takes the hexadecimal variable as an argument and returns the decimal value.

Output:

The above output verified that the hexadecimal value is converted to a decimal value.

Method 3: Using While Loop

In the example code below, the “while” loop is used to convert the hexadecimal value into decimal.

Code:

hex_value = '0A'

x = 0
count = 0
y = 0
len = len(hex_value) - 1
while len>=0:
    if hex_value[len]>='0' and hex_value[len]<='9':
        z = int(hex_value[len])
   
    elif hex_value[len]>='A' and hex_value[len]<='F':
        z = ord(hex_value[len]) - 55
   
    elif hex_value[len]>='a' and hex_value[len]<='f':
        z = ord(hex_value[len]) - 87
   
    else:
        x = 1
        break
    count = count + (z * (16 ** y))
    len = len - 1
    y = y+1
 
if x == 0:
    print("\nDecimal Value = ", count)
else:
    print("\nInvalid Input!")

In the above example:

  • The hexadecimal value is initialized and stored in a variable named “hex_val”.
  • The value of the variables “x”, “y”, and “count” is assigned to zero.
  • The “len()” accepts the hexadecimal variable as an argument and returns the length. The length value will be decremented and stored in a variable named “len”.
  • Next, the while loop condition is checked, and because the condition is “True”, the program control will jump inside the loop.
  • In the next step, the first “elif” statement becomes “True” according to the condition, so the statement written inside the “elif” block will be executed. The “ord()” function is used to represent the number of Unicode characters and subtract it from the “55”. The final result will be stored in a variable “z”.
  • Next, the statement “count = count +(z * (16**y))” will be executed, and the calculation will look like this “count = 0 + (10 * (16^0)) = 10”. The calculated value will be initialized in a variable “stored”.
  • Lastly, the length value will be decremented again, and this time the value of the “len” becomes “0”.
  • The loop will execute again and calculate the decimal value until the given “while” loop condition becomes “False”.
  • After the condition becomes false, the program exits while loop and moves to the next line where the “if” statement is used to check the initial condition of the variable “x”.
  • If the value of “x” is equal to zero, the statement written inside the loop will print the decimal value on the console screen otherwise, “invalid output” will be printed.

Output:

The above output verified that the hexadecimal had been converted into a decimal value.

Method 4: Using Dictionary

In the following examples, the “dictionary” is used along with the “for” loop to convert the hexadecimal digit into a decimal digit.

Code:

hex_table = {'0': 0, '1': 1, '2': 2, '3': 3,'4': 4, '5': 5, '6': 6, '7': 7,
        '8': 8, '9': 9, 'A': 10, 'B': 11,'C': 12, 'D': 13, 'E': 14, 'F': 15}

hexa_value = 'FE'
val = 0

len_val = len(hexa_value) - 1

for i in hexa_value:
    val = val + hex_table[i]*16**len_val
    len_val = len_val - 1

print('Hexadecimal Value: ', hexa_value)
print('\nDecimal Value: ', val)

In the above code:

  • The hexadecimal value digit from “0” to “9” and followed by “A” to “F” alphabet is initialized in the dictionary.
  • The hexadecimal value to be converted to decimal value is initialized in a variable named “hexa_value”. Assign the zero to a variable “val”.
  • The “len()” function calculates the length of the given hexadecimal value and decrements the value by “1”.
  • The “for” loop iterates over the input hexadecimal value, and the “val + hex_table[i]*16**len_val” statement will calculate the decimal value.

Output:

In the above output, the hexadecimal value has been converted into a decimal value.

That’s it from this guide!

Conclusion

To convert hexadecimal to decimal, the inbuilt “int()” function, “literal_eval()”, “while” loop, and “dictionary” is used in Python. The “int()” function takes a hexadecimal variable as the first argument and bases “16” in place of the second argument. Consequently, it converts the given hex value to decimal. The “literal_eval()” function is used to predict the base of the given input string number and convert it into a decimal value. The “while” loop and “dictionary” methods use various “conditions” and statements to convert the hexadecimal to decimal. This Python article presented a detailed guide on how to convert hex to decimal.