How to convert an int to a hex string?
The Python built-in function hex()
converts an integer to hexadecimal:
To get a hexadecimal string without the '0x' prefix:
And for uppercase hexadecimal representation:
For a hex string padded with zeros, use format specifiers:
Hex conversion using String Formatting
Different approaches exist in Python when it comes to formatting strings. Let's take a look.
%
-Style formatting:
.format()
and f-strings:
For lowercase hexadecimal:
For uppercase hexadecimal using f-strings:
Controlling the Width and Padding
Maintaining control over width and padding in hexadecimal string representations strikes a winning balance of precision and readability.
Padding with zeroes:
Setting minimum width:
Handling Large Numbers and the Role of chr()
Though chr()
is related to converting integers to single character strings, for hexadecimal conversions it might not be your first port of call.
chr()
with hex values:
For the ASCII value of a hexadecimal number within 255:
When dealing with big numbers:
For integers beyond 255, hex()
is your friend:
Navigating the ‘0x’ Prefix
The "0x" prefix signifies a hexadecimal number. Its visibility depends on your needs.
Without the 0x
:
With the 0x
:
Was this article helpful?