hex()

hex(x)
Returns: str · Added in v3.0 · Updated March 13, 2026 · Built-in Functions
conversion built-in hexadecimal formatting

The hex() function converts an integer to its hexadecimal (base-16) string representation. The output always includes the 0x prefix, which is standard for Python hexadecimal literals. This function is commonly used when working with color codes, memory addresses, cryptographic operations, or any scenario where hexadecimal representation is more readable or required.

Syntax

hex(x)

Parameters

ParameterTypeDefaultDescription
xintAn integer to convert to hexadecimal. Can be positive, negative, or zero.

Examples

Basic usage

# Converting a positive integer
hex(255)
# Output: '0xff'

hex(16)
# Output: '0x10'

hex(0)
# Output: '0x0'

Working with negative numbers

# Negative numbers include the negative sign
hex(-16)
# Output: '-0x10'

hex(-255)
# Output: '-0xff'

Practical example: color conversion

# Converting RGB values to hex color codes
def rgb_to_hex(r, g, b):
    return '#{:02x}{:02x}{:02x}'.format(r, g, b)

rgb_to_hex(255, 128, 0)
# Output: '#ff8000'

Working with byte values

# Displaying byte values in hexadecimal
data = [0, 16, 32, 64, 128, 255]
for byte in data:
    print(f'0x{byte:02x}')

# Output:
# 0x00
# 0x10
# 0x20
# 0x40
# 0x80
# 0xff

Common Patterns

Converting between number bases

# Convert to different bases
number = 255

hex(number)  # Base 16: '0xff'
bin(number)  # Base 2:  '0b11111111'
oct(number)  # Base 8:  '0o377'

Using with format strings

# Padding with zeros
for i in range(16):
    print(f'{i:02x}', end=' ')
# Output: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f

Errors

hex() raises a TypeError if the argument is not an integer:

hex('255')
# TypeError: 'str' object cannot be interpreted as an integer

hex(3.14)
# TypeError: 'float' object cannot be interpreted as an integer

hex(255.0)
# TypeError: 'float' object cannot be interpreted as an integer

See Also