Python
Programming
Hexadecimal Conversion
String Manipulation
Computer Science

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:

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

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

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 this works for hex strings of any length:

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

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:

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

If you want Python to infer the base automatically 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 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:

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

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:

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

A robust parsing function handles these edge cases:

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 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:

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, always wrap the conversion in a try/except or validate the string 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)

Negative Hex Values

A leading minus sign works as expected:

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

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:

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

For formatted output without the prefix, or with uppercase letters:

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)

Round-trip example:

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

Hex Strings vs. Raw Bytes

A common source of confusion is the difference between hex text and binary bytes:

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

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

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 Methods Comparison

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

Practical Examples

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]

Checksum Verification

python
1expected_crc = "a3f2b7c1"
2computed_crc = format(compute_crc32(data), '08x')
3if computed_crc == expected_crc:
4    print("Checksum matches")

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, 0x prefixes, and negative signs automatically.
  • Use base 0 when the input might be hex, octal, or binary and always carries the appropriate prefix.
  • Strip whitespace from external input before conversion. Catch ValueError for untrusted data.
  • Use hex() or format(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.

Course illustration
Course illustration

All Rights Reserved.