Python Reference ยท Built-in Functions
Python hex() function
Reference for Python hex(): convert an integer to a lowercase hexadecimal string with a 0x prefix, handle negatives, and format or parse hex values.
The hex() function converts an integer to a string of its value in base 16. The result is lowercase and always starts with the prefix 0x, which makes it a valid Python integer literal.
Hexadecimal is common for colors, memory addresses, byte values and bit masks. Use hex() when you want the prefix; use format() or an f-string when you need padding, uppercase letters or no prefix.
print(hex(255)) # 0xff print(hex(-26)) # -0x1a
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
hex(x)
| Name | Description |
|---|---|
x |
An int, or any object that defines __index__() returning an integer. |
Return value: a str such as '0x1f'. Negative numbers get a leading minus sign: '-0x1f'.
Raises: TypeError if x is not an integer, for example hex(3.5) or hex("10").
Usage notes
- Always lowercase with
0x. For uppercase digits call.upper()on the digits only, or use theXformat code:f"{255:X}"givesFF. - Padding needs
format().hex()does not pad.f"{n:04x}"pads to four digits;f"{n:#06x}"keeps the prefix and makes the whole string six characters wide. - Negative numbers are shown with a sign, not as two's complement. To see the byte pattern of a negative value, mask it first:
hex(-1 & 0xFF)gives'0xff'. - Floats are rejected. Use
float.hex()for the hexadecimal form of a float (see float methods). - Reverse conversion.
int("ff", 16)andint("0xff", 16)both parse hex text; base0reads the prefix to pick the base. - Bytes have their own method.
bytes.hex()turns raw bytes into a two-digits-per-byte string (see bytes methods). - Other bases:
bin()andoct()work the same way for base 2 and base 8.
Related
bin(),oct(),int(),format(),ord()- bytes and bytearray methods
- Lessons: Numbers, Bitwise operators