Hex to Decimal

Hex to decimal in Python

Type a hex value and pick a method. The code and its printed output update together.

int(x, 16)

Output:

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 too

A 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       # -100

For 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 first

bytes.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
FormatWidthSignedByte order
>H16-bitunsignedbig-endian
<H16-bitunsignedlittle-endian
>I32-bitunsignedbig-endian
>i32-bitsignedbig-endian
>Q64-bitunsignedbig-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")      # 255

Python'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 input

Common causes of ValueError:

  • Letters outside A–F, such as G or Z.
  • An empty string.
  • A missing 0x prefix 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
ExpressionOutputUse case
hex(n)0xffQuick check in the console
format(n, "X")FFClean uppercase for display
format(n, "04X")00FFFixed-width hex for byte values
f"{n:#x}"0xffInline 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.

MethodBest forHandles 0xSignedEndianness
int(s, 16)General conversionYesNoN/A
int(s, 0)Mixed bases (0x, 0o, 0b)RequiredNoN/A
int.from_bytesBinary data, byte arraysNo (use bytes.fromhex first)With signed=TrueYes
struct.unpackFixed-width binary protocolsNoFormat-dependentYes
ctypes.c_int32Quick signed castNoYesN/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?
Call 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?
Yes, 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?
Subtract 2ⁿ from the unsigned result when the top bit is set, where n is the bit width. 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?
Use 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?
Yes, Python integers have no fixed size. int("F" * 64, 16) returns the full 256-bit value (2²⁵⁶ − 1) with all 78 decimal digits, without overflow or loss of precision.