Convert a hex string to an int in Python
Codemia Knowledge Hub ·
Use int() with base 16:
The second argument tells int() to read the string as base 16. Without it, Python assumes base 10 and a string like "ff" raises ValueError. This one call handles uppercase, lowercase, 0x prefixes and negative signs.
How int(s, 16) behaves
The result is a normal Python int. Python integers have arbitrary precision, so hex strings of any length convert without overflow or truncation:
The 0x prefix
With base 16, int() accepts a 0x or 0X prefix:
To have Python infer the base from the prefix, use base 0:
Base 0 is useful when the input format varies and always carries a prefix. Without a prefix, base 0 treats the string as decimal.
Upper and lowercase digits
A-F and a-f are interchangeable, so no normalization is needed:
Negative values
A leading minus sign works, which helps when tools represent negative numbers in hex with a minus prefix:
Cleaning and validating external input
Hex strings from files, HTTP headers, command-line arguments or network protocols often carry whitespace:
A small parsing function can tolerate these artifacts:
You can extend it to reject empty strings, log errors or wrap ValueError in a domain-specific exception.
Characters outside 0-9, a-f and A-F raise ValueError:
For untrusted input, catch the exception or validate first:
Converting an int back to hex
Use the built-in hex():
For output without the prefix, in uppercase or zero-padded, use format:
A round trip:
Hex text vs raw bytes
Hex text is human-readable characters representing a number. Raw bytes are binary data. They need different functions, and mixing them up gives wrong results or errors:
Converting between the two:
Conversion functions at a glance
| 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 |
Examples: colors, addresses and checksums
Parsing color codes:
Reading memory addresses:
Parsing MAC addresses:
Verifying a checksum:
Mistakes that cause ValueError or wrong results
- Forgetting the base.
int("ff")raisesValueErrorbecause Python assumes base 10. Pass 16. - Confusing hex text with bytes.
int()with base 16 is for text like"ff";int.from_bytes()is for binary data likeb"\xff". - Not stripping external input. Call
.strip()on strings from files, HTTP responses or command-line arguments before parsing. - Using base 0 without a prefix.
int("10", 0)is read as decimal, not hex. If you know the input is hex, use base 16. - Not handling the exception. Python raises
ValueErrorimmediately on invalid input, so code that does not catch it crashes on malformed data.
Related reading
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.