hex()
Converts a whole number to a hexadecimal string that starts with 0x, such as 0xff for 255. Use int(text, 16) to convert back.
hex(x)Hexadecimal (base 16) writes numbers with the digits 0-9 and the letters a-f, where a is 10 and f is 15. hex() turns a whole number into that form, as a string with the prefix 0x: hex(255) is '0xff'.
Hex is everywhere in computing because two hex digits describe exactly one byte (0 to 255). You meet it in web colours (#ff8800), memory addresses, Unicode code points (U+20AC) and checksums.
hex() always uses lower-case letters and a prefix. For upper case, padding or no prefix, use format() with "x" or "X".
Parameters
| Parameter | What it is |
|---|---|
xrequired | A whole number (int). Floats are not accepted. |
Return value
A string starting with 0x (or -0x for negative numbers).
Examples
1Numbers in hex
for n in [9, 10, 15, 16, 255, 4096]:
print(n, hex(n))9 0x9 10 0xa 15 0xf 16 0x10 255 0xff 4096 0x1000
2Build a web colour code
Colours use two hex digits per channel. hex(0) is just 0x0, so use :02x to always get two digits.
r, g, b = 255, 136, 0
print(hex(r), hex(g), hex(b))
print(f"#{r:02x}{g:02x}{b:02x}")0xff 0x88 0x0 #ff8800
3From hex back to a number
print(int("ff", 16))
print(int("0x1F", 16))
print(0xFF)255 31 255
4Show the code point of a character
for ch in "A€":
print(hex(ord(ch)), f"U+{ord(ch):04X}")0x41 U+0041 0x20ac U+20AC
Combine with ord(): this is how character tables write Unicode numbers.
5Bytes as hex text
For a whole sequence of bytes, use the .hex() method of bytes() instead of hex() on each one.
data = "Hi!".encode("utf-8")
print(data.hex())
print(bytes.fromhex("486921"))486921 b'Hi!'
Common mistakes
Doing maths with the result
hex() returns text. hex(10) + hex(5) joins two strings. Do the maths on numbers and convert at the end.
print(hex(10) + hex(5))
print(hex(10 + 5))0xa0x5 0xf
Passing a float
hex(3.5) raises TypeError. Floats have their own method, (3.5).hex(), which shows the exact binary value in a special format.
try:
hex(3.5)
except TypeError:
print("TypeError: hex() needs an int")
print(hex(int(3.5)))TypeError: hex() needs an int 0x3
Questions people ask
How do I convert hex to decimal in Python?
int("ff", 16) gives 255. The prefix 0x is allowed in the text too.
How do I get upper-case hex without 0x?
format(255, "X") gives 'FF'; format(255, "04X") gives '00FF'.
How do I convert a string to hex?
Encode it to bytes, then call .hex(): "Hi".encode().hex() gives '4869'.