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

In Python, the standard way to convert a hexadecimal string to an integer is int(hex_string, 16). That handles uppercase or lowercase digits, optional 0x prefixes, and negative signs, so it is the normal answer unless you have a special parsing requirement.

The important part is the second argument. Without telling int() that the string is base 16, Python will treat ordinary digit strings as decimal by default.

The Standard Conversion

python
hex_string = "1a3f"
value = int(hex_string, 16)
print(value)

This prints 6719.

That is the normal and most readable approach.

Handling the 0x Prefix

Python accepts the usual hexadecimal prefix when you still provide base 16.

python
print(int("0x1a3f", 16))
print(int("0XFF", 16))

Both work correctly.

If you want Python to infer the base from prefixes such as 0x, 0o, or 0b, use base 0 instead.

python
print(int("0x1a3f", 0))

That is useful when the input format may vary and the prefix is part of the contract.

Case Does Not Matter

Hex digits A-F and a-f are treated the same way.

python
print(int("FF", 16))
print(int("ff", 16))
print(int("Ff", 16))

All of these return 255.

Normalize External Input

If the string comes from a file, command line, or network message, strip surrounding whitespace before converting.

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

That small normalization step prevents avoidable parsing failures caused by spaces or trailing newlines.

Negative Hex Strings Work Too

A leading minus sign is valid.

python
print(int("-0xA", 16))
print(int("-A", 16))

This is useful when textual protocols or tools represent signed values in hexadecimal form.

Invalid Input Raises ValueError

If the string is not valid hexadecimal, int() raises ValueError.

python
1try:
2    print(int("1z3f", 16))
3except ValueError:
4    print("Invalid hexadecimal string")

That is the correct behavior. If the input is external or untrusted, catch the exception or validate the text before converting.

The Reverse Operation

If you also need to convert an integer back to hexadecimal text, use hex().

python
number = 6719
print(hex(number))

This returns '0x1a3f'.

That makes simple round trips easy:

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

Hex Text Versus Raw Bytes

A common source of confusion is mixing up:

  • text like "ff"
  • bytes like b"\xff"

Those are different inputs. The first is hexadecimal text and should be parsed with int(..., 16). The second is raw binary data and may need int.from_bytes(...) or another byte-level API depending on the task.

A Small Parsing Helper

If hexadecimal parsing appears in several places, a helper function can make the accepted rules explicit.

python
1def parse_hex(text: str) -> int:
2    text = text.strip()
3    return int(text, 16)
4
5print(parse_hex(" ff "))
6print(parse_hex("0x2A"))

This is also a good place to normalize prefixes, reject empty strings, or wrap ValueError with a clearer application-specific error message.

Common Pitfalls

The biggest mistake is forgetting the base argument and writing int("ff"), which fails because Python assumes base 10. Another is confusing a hexadecimal text string with a bytes object. Developers also often forget to normalize whitespace when input comes from outside the program. Finally, if input quality is uncertain, do not assume every string is valid hex; catch ValueError and handle bad input explicitly.

Summary

  • Use int(hex_string, 16) for ordinary hexadecimal string conversion.
  • Python accepts uppercase, lowercase, optional 0x prefixes, and negative signs.
  • Use strip() when external input may contain whitespace.
  • Use base 0 if you want Python to infer the base from prefixes.
  • Catch ValueError when input may not be valid hexadecimal.

Course illustration
Course illustration

All Rights Reserved.