Convert Hex String to Int in Python



A Hexadecimal is the base-16 number system that uses the digits from the '0 to 9' and letters from 'A to F'. It is commonly used in the computers to represent the binary data in the readable format.

In this article we are going to learn about converting hex string into int. For example, if we receive the input as a hex string("12xf2") and need to convert it into a integer. For achieving this, Python provides the multiple methods let's explore them one by one.

Using Python int() Function

The Python int() function is used to convert a given value into an integer. It can convert various types of data, such as numeric strings or floating-point numbers, into integers.

Syntax

Following is the syntax for Python int() function -

int(value, base)

Example

Let's look at the following example, where we are going to convert the hex string to an integer using the int() function.

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

Output of the above program is as follows -

The given hex string is 
fe00
The resultant integer is 
65024

Using Python literal_eval() Method

The Python literal_eval() method is provided by the python Abstract Syntax Trees module, which is used to evaluate a string that contains a valid Python literal expression, such as numbers, strings, Boolean etc.

Syntax

Following is the syntax for Python literal_eval() method -

ast.literal_eval(expression)

Example

Consider the following example, where we are going to convert '0xfe00' to an integer using literal_eval() method.

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

Output

Output of the above program is as follows -

The given hex string is 
0xfe00
The resultant integer is 
65024

Using Python struct.unpack() Method

The Python struct module is used to work with the C binary data. It is used to convert between the Python values and C structs represented as python bytes objects.

The struct.unpack() method is used to unpack the binary data into a tuple of python values based on the given string.

Syntax

Following is the syntax for Python struct.unpack() method -

struct.unpack(format, buffer)

Example

In the following example, we are going to use the struct.unpack() method and convert '1A2D' to integer.

import struct
demo = "1A2D"
x = bytes.fromhex(demo)
result = struct.unpack(">H", x)[0]
print(result)

Output

Following is the output of the above program -

6701
Updated on: 2025-04-16T17:40:11+05:30

47K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements