Convert hex to decimal with int()
Call int() with the hex string as the first argument and 16 as the base. Python returns an integer with no size limit, so values of any length convert without overflow.
int("1A3F", 16) # 6719
int("ff", 16) # 255 — case does not matter
int("0xff", 16) # 255 — the 0x prefix is accepted
int("0xFF", 16) # 255 — mixed case works tooA hex literal written directly in code, such as 0xFF, is already an integer and does not need int(). Use int() only when the hex value is a string, for example from user input, a file or an API (Application Programming Interface) response.
Base 0: auto-detect the prefix
Pass base 0 to let Python read the prefix and pick the base automatically.
int("0x1A", 0) # 26 — hex (0x prefix)
int("0o17", 0) # 15 — octal (0o prefix)
int("0b1010", 0) # 10 — binary (0b prefix)Base 0 requires a prefix. int("1A", 0) raises a ValueError because Python cannot tell whether "1A" is hex or an invalid decimal. Try your own strings in the picture.
Signed hex to decimal
Python integers have no fixed width, so int("FF", 16) returns 255, not −1. To read a hex value as a signed two's complement number, subtract 2ⁿ when the top bit is set.
def signed_hex(hex_str, bits=32):
n = int(hex_str, 16)
if n >= (1 << (bits - 1)):
n -= (1 << bits)
return n
signed_hex("FF", 8) # -1
signed_hex("FF9C", 16) # -100
signed_hex("FFFFFFFF", 32) # -1
signed_hex("FF", 16) # 255 (00FF in 16 bits, sign bit is 0)The bits parameter must match the width of the type that produced the hex. FF is −1 at 8 bits and 255 at 16 bits.
The ctypes module offers a shorter route:
import ctypes
ctypes.c_int32(0xFFFFFFFF).value # -1
ctypes.c_int8(0xFF).value # -1
ctypes.c_int16(0xFF9C).value # -100For a full breakdown of sign bits and two's complement, see the signed hex to decimal converter.
Hex bytes to integer
Use bytes.fromhex() to convert a hex string to bytes, then int.from_bytes() to read those bytes as an integer. This method handles endianness and works with binary data from files, network packets and hardware registers.
data = bytes.fromhex("1A3F")
int.from_bytes(data, "big") # 6719 — most significant byte first
int.from_bytes(data, "little") # 16154 — least significant byte firstbytes.fromhex() requires an even number of hex digits. Pad a single digit with a leading zero: bytes.fromhex("0F").
struct.unpack for fixed widths
The struct module unpacks bytes into typed values with explicit byte order and width. The format string >H means big-endian unsigned 16-bit integer.
import struct
raw = bytes.fromhex("1A3F")
struct.unpack(">H", raw)[0] # 6719 — big-endian unsigned short
struct.unpack("<H", raw)[0] # 16154 — little-endian unsigned short
struct.unpack(">h", raw)[0] # 6719 — big-endian signed short| Format | Width | Signed | Byte order |
|---|---|---|---|
>H | 16-bit | unsigned | big-endian |
<H | 16-bit | unsigned | little-endian |
>I | 32-bit | unsigned | big-endian |
>i | 32-bit | signed | big-endian |
>Q | 64-bit | unsigned | big-endian |
Use struct.unpack when reading binary protocols, file headers or sensor data where the width and byte order are fixed.
Handling input formats
User input may include prefixes, spaces and mixed case. Strip and normalise the string before passing it to int().
def hex_to_dec(s):
s = s.strip()
if s.startswith(("#", "0x", "0X")):
s = s.lstrip("#").removeprefix("0x").removeprefix("0X")
return int(s, 16)
hex_to_dec("0xFF") # 255
hex_to_dec("#FF") # 255
hex_to_dec(" ff ") # 255
hex_to_dec("FF") # 255Python's int() already accepts the 0x prefix when the base is 16, but CSS colour codes use # instead, and input from forms often carries whitespace. The function above handles all three formats. It needs Python 3.9 or later for removeprefix().
Error handling
int() raises a ValueError when the string contains characters outside 0–9 and A–F. Wrap the call in a try/except block when the input comes from a user or an external source.
def safe_hex(s):
try:
return int(s.strip(), 16)
except ValueError:
return None
safe_hex("1A3F") # 6719
safe_hex("ZZZZ") # None — not a valid hex string
safe_hex("") # None — empty inputCommon causes of ValueError:
- Letters outside A–F, such as G or Z.
- An empty string.
- A missing
0xprefix with base 0:int("1A", 0). - A sign character in the wrong position:
int("1A-", 16).
Decimal to hex in Python
Use hex() to convert a decimal integer back to a hex string. The result is lowercase with a 0x prefix. Use format() or an f-string for other formats.
hex(255) # '0xff'
hex(-42) # '-0x2a'
format(255, "X") # 'FF' — uppercase, no prefix
format(255, "04X") # '00FF' — zero-padded to 4 digits
f"{255:#06x}" # '0x00ff' — prefix + padding| Expression | Output | Use case |
|---|---|---|
hex(n) | 0xff | Quick check in the console |
format(n, "X") | FF | Clean uppercase for display |
format(n, "04X") | 00FF | Fixed-width hex for byte values |
f"{n:#x}" | 0xff | Inline in strings with prefix |
For the full reverse conversion method and worked examples, see the decimal to hex converter.
Method comparison
Pick the method that matches your input. Start with int() and reach for struct or int.from_bytes only when byte order or fixed widths matter.
| Method | Best for | Handles 0x | Signed | Endianness |
|---|---|---|---|---|
int(s, 16) | General conversion | Yes | No | N/A |
int(s, 0) | Mixed bases (0x, 0o, 0b) | Required | No | N/A |
int.from_bytes | Binary data, byte arrays | No (use bytes.fromhex first) | With signed=True | Yes |
struct.unpack | Fixed-width binary protocols | No | Format-dependent | Yes |
ctypes.c_int32 | Quick signed cast | No | Yes | N/A |
Plain int(s, 16) covers most needs: plain hex strings, 0x-prefixed strings, mixed case, underscored groups and leading or trailing spaces.
Frequently asked questions
How do you convert hex to decimal in Python?
int("FF", 16) to convert the hex string "FF" to the decimal integer 255. The second argument, 16, tells int() the input is base 16 (hexadecimal).Does Python's int() accept the 0x prefix?
int("0xFF", 16) returns 255. The 0x prefix is optional when base 16 is specified. With base 0, the prefix is required.How do you convert signed hex to decimal in Python?
int("FF", 16) returns 255, and 255 - 256 gives −1 for an 8-bit signed value.What error does Python raise for invalid hex?
int() raises a ValueError with the message "invalid literal for int() with base 16". Catch it with a try/except ValueError block when the input is not guaranteed to be valid.How do you convert hex to decimal with little-endian byte order?
int.from_bytes(bytes.fromhex("FF1A"), "little") to read the bytes in little-endian order. The result is 6911 (0x1AFF), not 65306 (0xFF1A).Can Python handle large hex numbers?
int("F" * 64, 16) returns the full 256-bit value (2²⁵⁶ − 1) with all 78 decimal digits, without overflow or loss of precision.Related tools
- Hex to decimal converter — convert hex to decimal with digit-by-digit steps
- Signed hex to decimal — interpret hex as a signed two's complement integer
- Hex to decimal in JavaScript — parseInt, Number and BigInt methods
- Bulk hex to decimal — convert a list of hex values at once