The hex()
function is a built-in function in Python that returns a string representing a hexadecimal (base 16) value. It takes an integer as an argument and returns its hexadecimal representation.
Here's the syntax of the hex()
function:
hex(number)
The number
parameter is the integer you want to convert to a hexadecimal representation. It can be a positive or negative integer.
Here's an example that demonstrates the usage of the hex()
function:
decimal_number = 255
hexadecimal_number = hex(decimal_number)
print(hexadecimal_number) # Output: 0xff
In the example above, hex(decimal_number)
converts the decimal value 255 to its hexadecimal representation, which is "0xff". The resulting hexadecimal string is then printed.
It's important to note that the hex()
function always returns a string prefixed with "0x" to indicate that it represents a hexadecimal value. If you want to remove the "0x" prefix, you can use string manipulation techniques like slicing:
decimal_number = 255
hexadecimal_number = hex(decimal_number)[2:] # Remove the "0x" prefix
print(hexadecimal_number) # Output: ff
In this modified example, the [2:]
slicing operation is used to remove the first two characters from the hexadecimal string, resulting in "ff".