Python
Programming
Hexadecimal Conversion
String Manipulation
Computer Science

Convert a hex string to an int in Python

Codemia Knowledge Hub ·

Use int() with base 16:

python
value = int("1a3f", 16)  # 6719

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

python
1hex_string = "1a3f"
2value = int(hex_string, 16)
3print(value)   # 6719
4print(type(value))  # <class 'int'>

The result is a normal Python int. Python integers have arbitrary precision, so hex strings of any length convert without overflow or truncation:

python
large = int("ffffffffffffffffffffffffffffffff", 16)
print(large)  # 340282366920938463463374607431768211455

The 0x prefix

With base 16, int() accepts a 0x or 0X prefix:

python
print(int("0x1a3f", 16))   # 6719
print(int("0XFF", 16))     # 255
print(int("0xff", 16))     # 255

To have Python infer the base from the prefix, use base 0:

python
1print(int("0x1a3f", 0))    # 6719 (inferred hex)
2print(int("0o17", 0))      # 15  (inferred octal)
3print(int("0b1010", 0))    # 10  (inferred binary)
4print(int("42", 0))        # 42  (inferred decimal)

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:

python
1print(int("FF", 16))    # 255
2print(int("ff", 16))    # 255
3print(int("Ff", 16))    # 255
4print(int("aB", 16))    # 171

Negative values

A leading minus sign works, which helps when tools represent negative numbers in hex with a minus prefix:

python
print(int("-0xA", 16))   # -10
print(int("-ff", 16))    # -255

Cleaning and validating external input

Hex strings from files, HTTP headers, command-line arguments or network protocols often carry whitespace:

python
raw = "  0x2A\n"
value = int(raw.strip(), 16)
print(value)  # 42

A small parsing function can tolerate these artifacts:

python
1def parse_hex(text: str) -> int:
2    """Parse a hex string to int, tolerating whitespace and 0x prefix."""
3    text = text.strip()
4    if text.startswith(("0x", "0X")):
5        return int(text, 16)
6    return int(text, 16)

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:

python
1try:
2    value = int("1z3f", 16)
3except ValueError as e:
4    print(f"Invalid hex string: {e}")
5    # Output: Invalid hex string: invalid literal for int() with base 16: '1z3f'

For untrusted input, catch the exception or validate first:

python
1import re
2
3def is_valid_hex(s: str) -> bool:
4    """Check if string is valid hex, with optional 0x prefix."""
5    return bool(re.fullmatch(r'(0[xX])?[0-9a-fA-F]+', s.strip()))
6
7raw = "0xDEADBEEF"
8if is_valid_hex(raw):
9    value = int(raw.strip(), 16)

Converting an int back to hex

Use the built-in hex():

python
number = 6719
print(hex(number))       # '0x1a3f'

For output without the prefix, in uppercase or zero-padded, use format:

python
1print(format(255, 'x'))      # 'ff'
2print(format(255, 'X'))      # 'FF'
3print(format(255, '04x'))    # '00ff'  (zero-padded to 4 digits)
4print(f"{255:#06x}")         # '0x00ff' (prefix + padding)

A round trip:

python
1original = "0x1a3f"
2number = int(original, 16)
3back = hex(number)
4print(number, back)          # 6719 0x1a3f

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:

python
1# This is a hex STRING (text)
2hex_text = "ff"
3value = int(hex_text, 16)     # 255
4
5# This is a raw BYTE
6raw_byte = b"\xff"
7value = int.from_bytes(raw_byte, byteorder="big")  # 255

Converting between the two:

python
1# Hex string to bytes
2hex_str = "deadbeef"
3data = bytes.fromhex(hex_str)
4print(data)                   # b'\xde\xad\xbe\xef'
5
6# Bytes to hex string
7hex_back = data.hex()
8print(hex_back)               # 'deadbeef'
9
10# Bytes to integer
11value = int.from_bytes(data, byteorder="big")
12print(value)                  # 3735928559
13
14# Integer to bytes
15raw = value.to_bytes(4, byteorder="big")
16print(raw)                    # b'\xde\xad\xbe\xef'

Conversion functions at a glance

MethodInputOutputUse Case
int(s, 16)Hex string ("ff")intParsing hex text to a number
int(s, 0)Prefixed string ("0xff")intAuto-detect base from prefix
int.from_bytes(b, ...)bytes (b"\xff")intInterpreting raw binary data
hex(n)intHex string with 0xInteger to hex text
format(n, 'x')intHex string without prefixFormatted hex output
bytes.fromhex(s)Hex stringbytesHex text to binary data
b.hex()bytesHex stringBinary data to hex text

Examples: colors, addresses and checksums

Parsing color codes:

python
1def hex_to_rgb(color: str) -> tuple[int, int, int]:
2    """Convert a hex color like '#FF8800' or 'ff8800' to (R, G, B)."""
3    color = color.lstrip("#")
4    return (
5        int(color[0:2], 16),
6        int(color[2:4], 16),
7        int(color[4:6], 16),
8    )
9
10print(hex_to_rgb("#FF8800"))  # (255, 136, 0)
11print(hex_to_rgb("3a7bd5"))   # (58, 123, 213)

Reading memory addresses:

python
addresses = ["0x7ffeefbff8a0", "0x00400000", "0x7f0a3c000000"]
for addr in addresses:
    print(f"{addr} = {int(addr, 16)}")

Parsing MAC addresses:

python
mac = "00:1A:2B:3C:4D:5E"
octets = [int(byte, 16) for byte in mac.split(":")]
print(octets)  # [0, 26, 43, 60, 77, 94]

Verifying a checksum:

python
1import zlib
2
3data = b"hello world"
4expected_crc = "0d4a1185"
5computed_crc = format(zlib.crc32(data), '08x')
6if computed_crc == expected_crc:
7    print("Checksum matches")

Mistakes that cause ValueError or wrong results

  • Forgetting the base. int("ff") raises ValueError because 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 like b"\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 ValueError immediately on invalid input, so code that does not catch it crashes on malformed data.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Data 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.

Practice algorithms