Python hex()

The hex() function converts an integer number to the corresponding hexadecimal string.

The syntax of hex() is:

hex(x)

hex() Parameters

The hex() function takes a single argument.

x - integer number (int object or it has to define __index__() method that returns an integer)


Return Value from hex()

The hex() function converts an integer to the corresponding hexadecimal number in string form and returns it.

The returned hexadecimal string starts with prefix "0x" indicating it's in hexadecimal form.


Example 1: How hex() works?

number = 435
print(number, 'in hex =', hex(number))

number = 0
print(number, 'in hex =', hex(number))

number = -34
print(number, 'in hex =', hex(number))

returnType = type(hex(number))
print('Return type from hex() is', returnType)

When you run the program, the output will be:

435 in hex = 0x1b3
0 in hex = 0x0
-34 in hex = -0x22
Return type from hex() is <class 'str'>

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

Example 2: Hexadecimal representation of a float

number = 2.5
print(number, 'in hex =', float.hex(number))

number = 0.0
print(number, 'in hex =', float.hex(number))

number = 10.5
print(number, 'in hex =', float.hex(number))

When you run the program, the output will be:

2.5 in hex = 0x1.4000000000000p+1
0.0 in hex = 0x0.0p+0
10.5 in hex = 0x1.5000000000000p+3