hex() is a built-in Python function that converts an integer to its hexadecimal (base-16) string representation, prefixed with '0x' — a clean, readable way to inspect or manipulate binary/hex data. In 2026, hex() remains essential in data science (memory inspection, color codes, bit flags), software engineering (debugging, protocol parsing, cryptography), and low-level programming — fast, zero-overhead, and universally available. It works only on integers (int), raising TypeError on floats/strings; for negative numbers, it returns '-0x...'.
Here’s a complete, practical guide to using hex() in Python: basic conversion, formatting options, real-world patterns (earthquake bit flags, color encoding, memory dumps), and modern best practices with type hints, performance, alternatives (format, f-strings, binascii), and integration with NumPy/Dask/Polars/pandas.
Basic hex() usage — integer to hex string with '0x' prefix.
print(hex(255)) # '0xff'
print(hex(42)) # '0x2a'
print(hex(0)) # '0x0'
print(hex(-10)) # '-0xa'
print(hex(1 << 16)) # '0x10000'
Formatting hex strings — remove prefix, pad, uppercase, include '0x' explicitly.
n = 255
# Remove '0x' prefix
print(hex(n)[2:]) # 'ff'
# Uppercase
print(hex(n).upper()) # '0XFF'
# Pad with zeros to 8 hex digits
print(f"{n:08x}") # '000000ff' (f-string)
print(format(n, '08x')) # same
# Pad to 8 digits with '0x' prefix
print(f"0x{n:06x}") # '0x0000ff'
# With commas for large numbers (Python 3.6+)
large = 123456789
print(f"{large:x}") # '75bcd15'
print(f"{large:,x}") # '75,bcd,15' (comma separator)
Real-world pattern: earthquake bit flags & hex representation — parse, inspect, encode.
import pandas as pd
# Sample earthquake flags (bit positions: 0=shallow, 1=strong, 2=tsunami)
df = pd.DataFrame({
'event_id': [1, 2, 3],
'flags': [0b001, 0b011, 0b111] # binary flags
})
# Convert flags to hex for storage/inspection
df['flags_hex'] = df['flags'].apply(hex)
print(df[['event_id', 'flags', 'flags_hex']])
# event_id flags flags_hex
# 0 1 1 0x1
# 1 2 3 0x3
# 2 3 7 0x7
# Reverse: parse hex back to int
df['flags_back'] = df['flags_hex'].apply(lambda h: int(h, 16))
print((df['flags'] == df['flags_back']).all()) # True
# Bitwise check with hex literals
strong_mask = 0b010 # bit 1 = strong
df['is_strong'] = df['flags'] & strong_mask != 0
print(df)
Best practices for hex() in Python & data workflows. Use hex(n)[2:] — to strip '0x' prefix for clean hex strings. Modern tip: prefer f-strings — f"{n:08x}" for padding/formatting; faster & more readable than hex() + string ops. Use uppercase .upper() — for consistent hex output (common in crypto, memory dumps). Use int(hex_str, 16) — reverse conversion from hex string. Add type hints — def to_hex(n: int) -> str: return hex(n)[2:].upper(). Use in logging — logger.debug(f"Flags: {flags:08x}"). Use binascii.hexlify() — for bytes to hex (alternative to bytes.hex()). Use bytes.fromhex() — hex string to bytes. Use format(n, 'x') — alias for hex(n)[2:]. Use f"{n:x}" — no prefix, simplest formatting. Use f"{n:X}" — uppercase hex. Use f"{n:08X}" — padded uppercase. Use f"{n:#08x}" — padded with '0x' prefix. Use hex() in assertions — assert hex(flags) == '0x1f'. Use hex(id(obj)) — inspect object memory address. Use hex(sys.maxsize) — check system limits. Profile performance — hex() is fast; avoid in ultra-tight loops. Use binascii — for binary/hex conversions. Use struct — for packing/unpacking binary data with hex representation.
hex() converts integers to hexadecimal strings with '0x' prefix — use for debugging, logging, bit inspection, color codes, and memory dumps. In 2026, prefer f-strings for formatting, int(hex_str, 16) for reverse, NumPy/Polars/Dask for vectorized hex ops, and integrate with pandas pipelines. Master hex(), and you’ll handle binary/hex representation cleanly and efficiently in any numerical or data workflow.
Next time you need to see a number in hex — use hex(). It’s Python’s cleanest way to say: “Show me this integer in base 16 — simple and readable.”