Convert hex string to integer in Python
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
To convert a hexadecimal string to an integer in Python, use int() with base 16:
The second argument tells int() to interpret the string as base-16. Without it, Python defaults to base 10, and a string like "ff" would raise a ValueError. This one-liner handles uppercase, lowercase, 0x prefixes, and negative signs, covering virtually every format you will encounter.
The Standard Conversion
The result is a normal Python int. Python integers have arbitrary precision, so this works for hex strings of any length:
No overflow, no truncation. Python handles it natively.
Handling the 0x Prefix
Hex strings often come with a 0x or 0X prefix. Python's int() accepts both when you specify base 16:
If you want Python to infer the base automatically from the prefix, use base 0:
Base 0 is useful when your input format varies and the prefix is always present. Without a prefix, base 0 treats the string as decimal.
Case Insensitivity
Hex digits A-F and a-f are interchangeable:
No normalization step is needed before conversion.
Normalizing External Input
When hex strings come from files, HTTP headers, command-line arguments, or network protocols, they often carry whitespace or formatting artifacts:
A robust parsing function handles these edge cases:
You can extend this to reject empty strings, log errors, or wrap ValueError with a domain-specific exception.
Error Handling
If the string contains characters outside the hex range (0-9, a-f, A-F), int() raises a ValueError:
For untrusted input, always wrap the conversion in a try/except or validate the string first:
Negative Hex Values
A leading minus sign works as expected:
This is useful when parsing signed values from protocols or tools that represent negative numbers in hex with a minus prefix.
The Reverse Operation: Integer to Hex
Use the built-in hex() function:
For formatted output without the prefix, or with uppercase letters:
Round-trip example:
Hex Strings vs. Raw Bytes
A common source of confusion is the difference between hex text and binary bytes:
These are fundamentally different inputs. Hex text is human-readable characters that represent a number. Raw bytes are binary data. Mixing them up produces wrong results or errors.
Converting Between Hex Text and Bytes
Conversion Methods Comparison
| Method | Input | Output | Use Case |
int(s, 16) | Hex string ("ff") | int | Parsing hex text to a number |
int(s, 0) | Prefixed string ("0xff") | int | Auto-detect base from prefix |
int.from_bytes(b, ...) | bytes (b"\xff") | int | Interpreting raw binary data |
hex(n) | int | Hex string with 0x | Integer to hex text |
format(n, 'x') | int | Hex string without prefix | Formatted hex output |
bytes.fromhex(s) | Hex string | bytes | Hex text to binary data |
b.hex() | bytes | Hex string | Binary data to hex text |
Practical Examples
Parsing Color Codes
Reading Memory Addresses
Parsing MAC Addresses
Checksum Verification
Common Pitfalls
The most frequent mistake is forgetting the base argument: int("ff") raises ValueError because Python assumes base 10, and "ff" is not a valid decimal number. Always pass 16 as the second argument.
Confusing a hex text string ("ff") with a bytes literal (b"\xff") leads to using the wrong conversion function. int() with base 16 is for text. int.from_bytes() is for binary data.
Forgetting to strip whitespace from external input causes unnecessary ValueError exceptions. Always call .strip() on strings from files, HTTP responses, or command-line arguments before parsing.
Using int(s, 0) on a string without a prefix (like "10") silently interprets it as decimal, not hex. Base 0 auto-detection requires a prefix. If you know the input is hex, always use base 16 explicitly.
Assuming hex conversion can fail silently is wrong. Python raises ValueError immediately on invalid input. This is good behavior, but code that does not handle the exception will crash at runtime when given malformed data.
Summary
- Use
int(hex_string, 16)to convert a hex string to an integer. This is the standard, one-line answer. - Python handles uppercase, lowercase,
0xprefixes, and negative signs automatically. - Use base
0when the input might be hex, octal, or binary and always carries the appropriate prefix. - Strip whitespace from external input before conversion. Catch
ValueErrorfor untrusted data. - Use
hex()orformat(n, 'x')for the reverse operation (integer to hex string). - Do not confuse hex text strings with raw bytes. Use
int.from_bytes()for binary data.

