The hex(x) built-in function converts an integer number into its base-16 hexadecimal lowercase string representation prefixed with "0x".
Base-16 Representations & Colors: hex() accepts standard integers or any object defining the __index__() dunder method. For floating-point numbers, Python provides the dedicated float.hex() method. To format values without the leading "0x" or in uppercase, use format(). To convert integers into binary or octal representations, see bin() and oct().
The hex() function accepts an integer or indexable object and returns a string:
# Formal syntax of built-in hex()
hex_str = hex(x)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
x |
int or object with __index__() |
An integer number. Floating-point numbers raise a TypeError. |
| Return Value | str |
A lowercase string representing the hexadecimal value prefixed with "0x" (e.g. "0x1b"). |
Standard decimal integers are converted directly into base-16 strings. Negative numbers preserve their minus sign before the prefix:
# 1. Standard integer hexadecimal conversion
my_num = 27
print("hex(27): ", hex(my_num)) # 0x1b
# 2. Negative integer conversion
neg_num = -27
print("hex(-27):", hex(neg_num)) # -0x1b
# 3. Converting zero
print("hex(0): ", hex(0)) # 0x0
Output:
hex(27): 0x1b
hex(-27): -0x1b
hex(0): 0x0
Because Python stores integers internally as binary values, you can pass binary (0b...) and octal (0o...) literals directly to hex():
# Inter-base translations in Python
# Integer 27 represented across different bases:
bin_val = 0b11011 # Binary 27
oct_val = 0o33 # Octal 27
dec_val = 27 # Decimal 27
print("Binary to Hex: ", hex(bin_val)) # 0x1b
print("Octal to Hex: ", hex(oct_val)) # 0x1b
print("Decimal to Hex:", hex(dec_val)) # 0x1b
Output:
Binary to Hex: 0x1b
Octal to Hex: 0x1b
Decimal to Hex: 0x1b
To remove the "0x" prefix, pad digits with leading zeros, or display uppercase letters (A–F), use format() or f-string specifiers:
# Prefix stripping, format(), and upper/lowercase casing
number = 255
# Method 1: Slicing the output string
raw_hex = hex(number)
print("Sliced string: ", raw_hex[2:])
# Method 2: format() built-in with lowercase 'x' and uppercase 'X'
print("format(255, 'x') lower:", format(number, 'x'))
print("format(255, 'X') upper:", format(number, 'X'))
# Method 3: Modern f-string specifiers
print("f'{255:#x}' with prefix: ", f"{number:#x}")
print("f'{255:04x}' padded hex: ", f"{number:04x}")
Output:
Sliced string: ff
format(255, 'x') lower: ff
format(255, 'X') upper: FF
f'{255:#x}' with prefix: 0xff
f'{255:04x}' padded hex: 00ff
Passing a float to the built-in hex() function raises a TypeError. To inspect floating-point numbers in exact hexadecimal format without rounding errors, use the float.hex() method:
# Floating-point numbers: float.hex() method
# Note: calling built-in hex(27.45) raises TypeError!
pi_approx = 3.141592653589793
hex_float = pi_approx.hex()
print("Float hexadecimal representation:", hex_float)
# Exact lossless reconstruction from float hex
restored_float = float.fromhex(hex_float)
print("Restored original float: ", restored_float)
Output:
Float hexadecimal representation: 0x1.921fb54442d18p+1
Restored original float: 3.141592653589793
Classes representing hardware registers, memory offsets, or pointers can support hex() by implementing __index__():
# Custom classes implementing __index__()
class MemoryAddress:
def __init__(self, addr: int):
self.addr = addr
def __index__(self) -> int:
return self.addr
mem = MemoryAddress(4096)
print("Memory object type:", type(mem))
print("hex(mem) output: ", hex(mem))
Output:
Memory object type:
hex(mem) output: 0x1000
Hexadecimal representation is ubiquitous in web design for RGB colors and in network systems for byte serialization:
# Recipe A: Hexadecimal color codes to RGB tuples
def hex_to_rgb(hex_code: str) -> tuple[int, int, int]:
clean_hex = hex_code.lstrip('#')
return tuple(int(clean_hex[i:i+2], 16) for i in (0, 2, 4))
def rgb_to_hex(r: int, g: int, b: int) -> str:
return f"#{r:02x}{g:02x}{b:02x}"
sample_color = "#FF65AA"
rgb_tuple = hex_to_rgb(sample_color)
print(f"{sample_color} -> RGB: {rgb_tuple}")
print(f"Reconstructed Hex: {rgb_to_hex(*rgb_tuple)}")
Output:
#FF65AA -> RGB: (255, 101, 170)
Reconstructed Hex: #ff65aa
# Recipe B: Raw byte hex dumping and UUID formatting
raw_bytes = b"Hello, Python!"
hex_stream = raw_bytes.hex()
print("Raw byte hex string: ", hex_stream)
# Converting hex string back into bytes
restored_bytes = bytes.fromhex(hex_stream)
print("Restored original bytes: ", restored_bytes)
# Decoding integer back from hex string
val = int("0x1b", 16)
print("int('0x1b', 16) decimal: ", val)
Output:
Raw byte hex string: 48656c6c6f2c20507974686f6e21
Restored original bytes: b'Hello, Python!'
int('0x1b', 16) decimal: 27
hex(3.14) raises TypeError. Use (3.14).hex() or hex(int(3.14)) instead.hex(-10) yields '-0xa', not two's complement. To obtain two's complement hex, apply a bitmask like hex(-10 & 0xffffffff).int(s, 16), Python accepts both uppercase and lowercase digits seamlessly.# Pitfall 1: Float inputs to built-in hex() raise TypeError
try:
hex(27.45)
except TypeError as err:
print("TypeError caught:", err)
# Pitfall 2: Python 2 legacy hex long literals ('0x1bL') are obsolete
# In Python 3, integers have arbitrary precision and never append 'L'
large_num = 2**64
print("64-bit integer hex:", hex(large_num))
Output:
TypeError caught: 'float' object cannot be interpreted as an integer
64-bit integer hex: 0x10000000000000000
Practice base conversions, RGB color translations, and byte stream serializations in our companion Jupyter Notebook:
Explore interactive code cells, convert hex color codes to RGB tuples, test float.hex() lossless math, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify hex() mechanics:
def test_hex_mechanics():
# 1. Standard integers
assert hex(27) == "0x1b"
assert hex(-27) == "-0x1b"
assert hex(0) == "0x0"
# 2. Inter-base literals
assert hex(0b11011) == "0x1b"
assert hex(0o33) == "0x1b"
# 3. int(s, 16) round-trip
assert int(hex(1024), 16) == 1024
# 4. Custom class __index__
class Address:
def __index__(self):
return 255
assert hex(Address()) == "0xff"
print("All hex() unit assertions passed! 100% verified.")
test_hex_mechanics()
Output:
All hex() unit assertions passed! 100% verified.
Converts an integer to a binary string prefixed with 0b.
Converts an integer to an octal string prefixed with 0o.
Parses integer values from strings in arbitrary bases (base 2 to 36).
Formats numbers into lowercase or uppercase hexadecimal without prefixes.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.