The hex function in Python is utilized to produce the hexadecimal representation of an integer input. It accepts an integer parameter and yields a string that represents the integer in hexadecimal format. If you need to obtain the hexadecimal value of a floating-point number, you should utilize the float.hex method. Below is the function's signature.
Python hex Function Syntax
It has the following syntax:
hex (integer)
Parameters
- integer: This represents an integer that will be transformed into a hexadecimal string.
Return
It returns a hexadecimal string.
Different Examples for Python hex Function
Let’s explore a few instances of the hex function to grasp its capabilities.
Python hex Function Example 1
An uncomplicated illustration to obtain the hexadecimal representation of decimal integers.
# Python hex() function example
# Calling function
result = hex(1) # integer value
result2 = hex(342)
# Displaying result
print(result)
print(result2)
Output:
0x1
0x156
Python hex Function Example 2
It exclusively accepts an integer argument; if any other type is provided, it will generate an error message in the console.
# Python hex() function example
# Calling function
result = hex(1.5) # float value
# Displaying result
print(result)
Output:
TypeError: 'float' object cannot be interpreted as an integer
Python hex Function Example 3
To obtain the hexadecimal representation of a float, you can utilize the method float.hex. This method executes without raising any exceptions. Refer to the example provided below.
# Python hex() function example
# Calling function
result = float.hex(1.5) # float value
result2 = float.hex(-238.15) # float value
# Displaying result
print(result)
print(result2)
Output:
0x1.8000000000000p+0
-0x1.dc4cccccccccdp+7