hex() function in Python
hex() function in Python is used to convert an integer to its hexadecimal equivalent. It takes an integer as input and returns a string representing the number in hexadecimal format, starting with "0x" to indicate that it's in base-16. Example:
a = 255
res = hex(a)
print(res)
Output
0xff
Explanation: hex() function takes that number and converts it into its hexadecimal representation, which is 0xff. The result is stored in res.
Syntax of hex()
hex(x)
Parameter: x is an integer number (of type int).
Returns: A string representing the hexadecimal form of the integer. The string is prefixed with 0x, indicating that it is in base-16.
Examples of hex()
Example 1: In this example, we convert an ASCII character and a floating-point number to their corresponding hexadecimal values.
print(hex(ord('a')))
print(float.hex(3.9))
Output
0x61 0x1.f333333333333p+1
Explanation:
- ord('a') converts the character 'a' to its ASCII value, which is 97.
- hex(ord('a')) converts the ASCII value 97 into its hexadecimal equivalent 0x61.
- float.hex(3.9) converts the floating-point number 3.9 into its hexadecimal representation 0x1.f333333333333p+1.
Example 2: In this example, we perform bitwise AND and bitwise OR operations on two hexadecimal numbers a and b. The results are then converted to hexadecimal format.
a = 0x22
b = 0x0A
# Bitwise AND and OR
print(hex(a & b))
print(hex(a | b))
Output
0x2 0x2a
Explanation:
- AND (a & b) and OR (a | b) operations on a (0x22) and b (0x0A), resulting in 0x02 (2 in decimal) and 0x2A (42 in decimal), respectively.
- hex(a & b) prints 0x2 and hex(a | b) prints 0x2a, converting the results into hexadecimal format.
Example 3: In this example, we convert a large integer to its corresponding hexadecimal value using the hex() function.
a = 987654321
res = hex(a)
print(res)
Output
0x3ade68b1
Explanation: hex(a) convert 987654321 to its hexadecimal representation.
Error and Exceptions
hex() function raises a TypeError if a non-integer (e.g., a float or string) is passed as an argument.
print(hex(11.1))
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 1, in <module>
print(hex(11.1))
~~~^^^^^^
TypeError: 'float' object cannot be interpreted as an integer
To convert a float to hexadecimal, use the float.hex() method instead.
print(float.hex(11.1))
Output
0x1.6333333333333p+3