Skip to content

Python hex() Function

Learn how to use Python's built-in hex() function to convert integers (including binary, octal, and hexadecimal inputs) into lowercase hexadecimal strings prefixed with 0x, along with examples and parameter details.

The hex() function in Python is a built-in function that converts an integer to a lowercase hexadecimal string prefixed with 0x. This function can also accept objects that define an __index__() function, which returns an integer.

Syntax

hex(x)

hex() Parameters

Python hex() function parameters:

Parameter Condition Description
x Required An integer or an object with an __index__() method that returns an integer

hex() Return Value

The hex() function returns a hexadecimal string representation of the given number.

Examples

Example 1: Converting Integer to Hexadecimal with hex() function

print(hex(255))     # Output:  0xff
print(hex(125))     # Output:  0x7d
print(hex(12345))   # Output:  0x3039
print(hex(0))       # Output:  0x0
print(hex(-123))    # Output:  -0x7b

output

0xff
0x7d
0x3039
0x0
-0x7b

Example 2: Converting Float to Hexadecimal with hex() function

If you need to find a hexadecimal representation of a float, you need to use float.hex() method

print(float.hex(2.5))   # Output: 0x1.4000000000000p+1
print(float.hex(0.0))   # Output: 0x0.0p+0
print(float.hex(10.5))  # Output: 0x1.5000000000000p+3

output

0x1.4000000000000p+1
0x0.0p+0
0x1.5000000000000p+3

Example 3: Converting Binary to Hexadecimal with hex() function

print(hex(0b101))   # Output:  0x5
print(hex(0b100))   # Output:  0x4
print(hex(0b1110))  # Output:  0xe
print(hex(0b10011)) # Output:  0x13
print(hex(0b00000)) # Output:  0x0
print(hex(0b11111)) # Output:  0x1f

output

0x5
0x4
0xe
0x13
0x0
0x1f

Example 4: Converting Octal to Hexadecimal with hex() function

print(hex(0o47))    # Output:  0x27
print(hex(0o237))   # Output:  0x9f
print(hex(0o111))   # Output:  0x49
print(hex(0o2345))  # Output:  0x4e5
print(hex(0o34567)) # Output:  0x3977
print(hex(0o77777)) # Output:  0x7fff

output

0x27
0x9f
0x49
0x4e5
0x3977
0x7fff

Example 5: Converting Hexadecimal to Hexadecimal with hex() function

It makes no sense, but it's possible 😅.

print(hex(0XFF))    # Output:  0xff
print(hex(0XABC))   # Output:  0xabc
print(hex(0XFFFF))  # Output:  0xffff

output

0xff
0xabc
0xffff

Example 6: Using hex() with Custom Objects

class Data:
    id =  0

    def __index__(self):
        return self.id

d = Data()
d.id =  100

print(hex(d))  # Output:  0x64

output

0x64
Navigation