Tutorial Study Image

Python hex()

The hex() function helps for the conversion of the given number into its corresponding hexadecimal string format. The returned hexadecimal string must have the prefix as '0x'.

hex(number) #Where number shows a integer number

hex()  Parameters:

Takes only one parameter. If we are passing an object as the parameter to hex() function that object must have __index__() function defined that returns integer. 

Parameter Description Required / Optional
object int object or it has to define __index__() method that returns an integer Optional
integer number can be in any base such as binary, octal, etc Optional

hex()  Return Value

For getting a hexadecimal representation of a float number needs to use float.hex() method.

Input Return Value
Integer hexadecimal format
float hexadecimal format
object hexadecimal format

Examples of hex()  method in Python

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)


435 in hex = 0x1b3
0 in hex = 0x0
-34 in hex = -0x22
Return type from hex() is 

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))


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

Example 3: How hex() works with objects?

class Data:
    id = 0

    def __index__(self):
        print('__index__ function called')
        return self.id

d = Data()
d.id = 100



__index__ function called