Python hex()
Function
The hex() function in Python is used to convert an integer number to a hexadecimal string (base 16), prefixed with 0x
.
This is useful when working with colors, memory addresses, or binary data formats.
Syntax
hex(number)
Parameters:
number
– A valid integer (positive or negative)
Returns:
- A string starting with
'0x'
followed by the hexadecimal equivalent of the integer.
Example: Convert Positive Integer to Hex
print(hex(255))
0xff
Example: Convert Negative Integer to Hex
print(hex(-42))
-0x2a
Use Case: RGB Colors in Web Design
Each color component in an RGB color code is often represented in hexadecimal:
r = 255
g = 165
b = 0
hex_color = f"#{hex(r)[2:]}{hex(g)[2:]}{hex(b)[2:]}"
print(hex_color)
#ffa500
Note: [2:]
is used to remove the '0x'
prefix.
Common Mistakes
- Passing a float:
hex(3.14)
will raiseTypeError
- Passing a string:
hex("10")
is invalid - Always pass an integer type: use
int()
if needed
Interview Tip
In interviews, hex()
is often used in bit manipulation or encoding problems. Know how to combine it with int()
, bin()
, or ord()
.
Summary
hex()
converts an integer to a base-16 (hexadecimal) string- Output starts with
'0x'
for positive or'-0x'
for negative - Does not work on float or string types directly
Practice Problem
Write a program that reads an integer from the user and prints its hexadecimal equivalent.
num = int(input("Enter an integer: "))
print("Hexadecimal:", hex(num))