How to convert hex string into int in Python?

PythonServer Side ProgrammingProgramming

A string is a group of characters that can be used to represent a single word or an entire phrase. Strings are simple to use in Python since they do not require explicit declaration and may be defined with or without a specifier.

In Python, the class named string represents the strings. This class provides several built-in methods, using these methods we can perform various operations on strings.

In this article, we are going to find out how to convert hex string into an integer in Python.

Using the int() method

One way to achieve this is using the inbuilt integer type casting method int(). We have 2 parameters, the first one being string and the next one is the base which the given string is in i.e. you have to pass 16 as second parameter since the input string is hex string.

If there is a prefix of “0x” for the given hex string, then we have to send the second parameter as 0 instead of 16.

Example 1

In the program given below, we are taking a hex string as input and we are converting into an integer using the int() typecasting method with base 16.

hex_str = "fe00" print("The given hex string is ") print(hex_str) res = int(hex_str,16) print("The resultant integer is ") print(res)

Output

The output of the above given example is,

The given hex string is
fe00
The resultant integer is
65024

Example 2

In the example given below, we are taking a hex string with prefix 0x as input and we are converting it into an integer using the int() method with base 0.

hex_str = "0xfa22" print("The given hex string is ") print(hex_str) res = int(hex_str,0) print("The resultant integer is ") print(res)

Output

The output of the above program is,

The given hex string is
0xfa22
The resultant integer is
64034

Using the literal_eval() method

You can convert the hexstring to an integer in Python using the literal_eval() method of the ast (Abstract Syntax Trees) library. We have to pass the hex string to the literal_eval() function, there are no parameters, the function converts the hex string into an integer.

Example

In the example given below, we are converting the hex string into an integer using the literal_eval() method of ast library.

from ast import literal_eval hex_str = "0xfe00" print("The given hex string is ") print(hex_str) res = literal_eval(hex_str) print("The resultant integer is ") print(res)

Output

The output of the above example is,

The given hex string is
0xfe00
The resultant integer is
65024
raja
Updated on 26-Oct-2022 07:02:20

Advertisements