Explain Codes LogoExplain Codes Logo

How to convert an int to a hex string?

python
formatting-strings
hex-conversion
python-3
Alex KataevbyAlex Kataev·Jan 10, 2025
TLDR

The Python built-in function hex() converts an integer to hexadecimal:

hex_value = hex(255) print(hex_value) # "0xff", voilà!

To get a hexadecimal string without the '0x' prefix:

hex_str = format(255, 'x') print(hex_str) # "ff", because who needs prefixes anyway?

And for uppercase hexadecimal representation:

hex_upper = format(255, 'X') print(hex_upper) # "FF", because shout it loud!

For a hex string padded with zeros, use format specifiers:

hex_padded = format(255, '04x') print(hex_padded) # "00ff", zero to hero!

Hex conversion using String Formatting

Different approaches exist in Python when it comes to formatting strings. Let's take a look.

%-Style formatting:

hex_format = "%0.2X" % 255 print(hex_format) # "FF", nice and clean!

.format() and f-strings:

For lowercase hexadecimal:

hex_formatted = "{:02x}".format(255) print(hex_formatted) # "ff", small yet mighty!

For uppercase hexadecimal using f-strings:

hex_fstring = f"{255:02X}" print(hex_fstring) # "FF", louder for the folks in the back!

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:

# Using format() padded_hex = format(255, '0>4X') print(padded_hex) # "00FF" # Using an f-string padded_fstring = f"{255:04x}" print(padded_fstring) # "00ff"

Setting minimum width:

# Padding with enough zeroes to reach min width, but no '0x' prefix min_width = "{:0>4x}".format(255) print(min_width) # "00ff" # Now with a '0x' prefix min_width_prefix = "0x{:0>4x}".format(255) print(min_width_prefix) # "0x00ff"

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:

char_repr = chr(65) hex_repr = format(ord(char_repr), 'x') print(char_repr, hex_repr) # "A 41", ASCII in disguise!

When dealing with big numbers:

For integers beyond 255, hex() is your friend:

large_hex = format(4096, 'x') print(large_hex) # "1000", now that's what I call a large number!

The "0x" prefix signifies a hexadecimal number. Its visibility depends on your needs.

Without the 0x:

no_prefix_hex = hex(255)[2:] print(no_prefix_hex) # "ff", you've lost the glasses!

With the 0x:

with_prefix_hex = "0x" + format(255, 'x') print(with_prefix_hex) # "0xff", visibility is key!