How to convert hex to decimal python

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:

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.

Читайте также:  Printing classes in python

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.

# 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)
  • 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.

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.

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)
  • 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.

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.

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]='A' and hex_value[len]='a' and hex_value[len]
  • 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.

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.

hex_table = 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)
  • 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.

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

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.

Источник

4 Best Ways to Convert Hexadecimal to Decimal in Python

python Hexadecimal to decimal

In python, we have been discussing many concepts. Sometimes, we occur in a situation where we need to find the decimal value of the hexadecimal number. So In this tutorial, we will be discussing the conversion of hexadecimal to decimal in python. As the conversion of elements has been a handy utility as it offers it in a much simpler way than other languages.

What is hexadecimal to decimal conversion in Python?

Hexadecimal to Decimal conversion is the conversion in which we will convert the hexadecimal string into a decimal value with the help of different functions and different ways.

The hexadecimal number system is the numeral system made up of 16 characters or symbols. It is also known by the name hex in the python programming language.

4 Different ways to convert hexadecimal to decimal in Python

Here, we will be discussing all the ways through which we can convert hexadecimal to decimal value:

1. Using int() for Converting hexadecimal to decimal in Python

Python module provides an int() function which can be used to convert a hex value into decimal format. It accepts 2 arguments, i.e., hex equivalent and base, i.e. (16).

int() function is used to convert the specified hexadecimal number prefixed with 0x to an integer of base 10.

If the hexadecimal number is in the form of string format, then the second parameter must identify the base, i.e., 16 of the specified number in string format. Let us look at the example for understanding the concept in detail.

# hexadecimal string hex = '0F' # conversion dec = int(hex, 16) print('Value in hexadecimal:', hex) print('Value in decimal:', dec)
Value in hexadecimal: 0F Value in decimal: 15

Explanation:

  • Firstly, we will take the hexadecimal input in the variable hex.
  • Then, we will apply the int() function.
  • Inside which we have passed both the parameters.
  • At last, we have printed the hexadecimal value and the converted decimal value.
  • Hence, you can see both the values in the output.

2. Using ast.literal_eval() for Converting hexadecimal to decimal in Python

In this example, we will be using the literal evaluation function, which helps us to predict the base and converts the number string to its decimal number format. The literal_eval() function is available in ast module. Let us look at the example for understanding the concept in detail.

#import literal_eval from ast module from ast import literal_eval string = '0xF' # conversion dec = literal_eval(string) print("The hexadecimal string is: ", string) print("The decimal number is: ", dec)
The hexadecimal string is : 0xF The decimal number is : 15

Explanation:

  • Firstly, we will import the literval_eval() function from the ast library,
  • Then, we will take the hexadecimal string in the string variable.
  • After that, we will apply the literal_eval() function.
  • Literal_eval() function will predict the base and converts the number string to its decimal number format.
  • At last, we will print the hexadecimal value and the converted decimal value.
  • Hence, you can see both the values in the output.

3. Using a dictionary for Converting hexadecimal to decimal in Python

In this example, we will be using a dictionary to convert hexadecimal to decimal. We will be making a dictionary in which we will write all the predefined values of the hexadecimal table in it. After that, we will apply for loop and convert the values into the required format. Let us look at the example for understanding the concept in detail.

 
hex = input("Enter the hexadecimal number: ").strip().upper() dec = 0 #computing max power value length = len(hex) -1 for digit in hex: dec += hex_to_dec_table[digit]*16**length length -= 1 print("Decimal value is : ",dec)
Enter the hexadecimal number: af Decimal value is : 175

Explanation:

  • Firstly, we will define the dictionary with the decimal related to hexadecimal values in the variable hex_to_dec_table.
  • Then, we will take the input from the user and convert it into the uppercase format.
  • We will take a variable dec which is set to 0.
  • Then, we will calculate the max power value inside the variable named length.
  • After that, we will apply for loop with the given conditions.
  • At last, we will print the dec value, which is also called the decimal value.
  • Hence, you can see the converted value as the output.

4. Using while loop for Converting hexadecimal to decimal in Python

In this example, we will be using a while loop to convert hexadecimal to a decimal value. Firstly, we will take the hexadecimal input. Then, we will take three variables, c, count, and ‘i’, all equal to 0. After that, we will apply while loop with all the conditions inside it. At last, we will check the value of c. If it is equal to 0, we will print the value of the count—otherwise, invalid input. Let us look at the example for understanding the concept in detail.

hex = input("Enter Hexadecimal Number: ") c = count = i = 0 len = len(hex) - 1 while len>=0: if hex[len]>='0' and hex[len]='A' and hex[len]='a' and hex[len]
Enter Hexadecimal Number: ff Decimal Value = 255

Explanation:

  • Firstly, we will take the hexadecimal input from the user.
  • Then, we will take three variables, c, count, and I, which are set to 0.
  • Then, we will calculate the max power value inside the variable named length.
  • After that, we will apply the while loop with the given condition inside it.
  • Then, we will check if the value of c is equal to 0, we will print the value of count. Otherwise, invalid input.
  • Hence, you can see the decimal value as the output.

Conclusion

In this tutorial, we have learned about the concept of converting a hexadecimal value to a decimal value. We have seen all the ways through which we can convert hexadecimal to a decimal value. All the ways are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Источник

Оцените статью