The hex()
function in Python is a built-in function that converts an integer number into a lowercase hexadecimal string prefixed with '0x'. This function takes an integer as an argument and returns the corresponding hexadecimal representation of the number.
Parameter Values
Parameter | Description |
---|---|
number | An integer number (in decimal or in another base) to convert into a hexadecimal string. |
Return Values
The hex()
function returns a string representation of an integer in hexadecimal.
How to Use hex()
in Python
Example 1:
The hex()
function converts an integer number to a lowercase hexadecimal string prefixed with '0x'.
num = 255
hex_num = hex(num)
print(hex_num) # Output: '0xff'
Example 2:
The hex()
function also works with negative numbers.
num = -42
hex_num = hex(num)
print(hex_num) # Output: '-0x2a'
Example 3:
You can use hex()
with bitwise operators to manipulate binary data.
num1 = 0b1010
num2 = 0b1100
hex_num = hex(num1 ^ num2)
print(hex_num) # Output: '0x6'