Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert hex string into int in Python?
A Hexadecimal is the base-16 number system that uses the digits from '0 to 9' and letters from 'A to F'. It is commonly used in computers to represent binary data in a readable format.
In this article, we will learn about converting hex strings into integers. For example, if we receive input as a hex string ("fe00") and need to convert it into an integer, Python provides multiple methods. Let's explore them one by one.
Using int() Function
The int() function is the most common method to convert a hex string to an integer. It accepts a base parameter to specify the number system.
Syntax
int(value, base)
Example
Let's convert a hex string to an integer using the int() function ?
hex_str = "fe00"
print("The given hex string is:", hex_str)
result = int(hex_str, 16)
print("The resultant integer is:", result)
The given hex string is: fe00 The resultant integer is: 65024
Using literal_eval() Method
The literal_eval() method from the ast module evaluates a string containing a valid Python literal expression. For hex conversion, the string must include the '0x' prefix.
Syntax
ast.literal_eval(expression)
Example
Convert '0xfe00' to an integer using literal_eval() method ?
import ast
hex_str = "0xfe00"
print("The given hex string is:", hex_str)
result = ast.literal_eval(hex_str)
print("The resultant integer is:", result)
The given hex string is: 0xfe00 The resultant integer is: 65024
Using struct.unpack() Method
The struct module works with binary data and can convert hex strings to integers. First, convert the hex string to bytes, then unpack it using a format specifier.
Syntax
struct.unpack(format, buffer)
Example
Convert '1A2D' to an integer using struct.unpack() method ?
import struct
hex_str = "1A2D"
print("The given hex string is:", hex_str)
# Convert hex string to bytes
hex_bytes = bytes.fromhex(hex_str)
# Unpack as unsigned short (2 bytes, big-endian)
result = struct.unpack(">H", hex_bytes)[0]
print("The resultant integer is:", result)
The given hex string is: 1A2D The resultant integer is: 6701
Comparison
| Method | Requires Prefix | Best For |
|---|---|---|
int() |
No | Simple hex string conversion |
literal_eval() |
Yes (0x) | Safe evaluation of literals |
struct.unpack() |
No | Binary data processing |
Conclusion
Use int(hex_string, 16) for simple hex to integer conversion. Use literal_eval() for safe evaluation when the string includes '0x' prefix. Use struct.unpack() when working with binary data formats.
