How to Convert a Number to a Hex String in Python

Updated: June 3, 2023 By: Khue Post a comment

This pithy article shows you how to turn a number (integer, float) into a hexadecimal value in Python.

Convert an integer to a hex value

You can use the hex() function to convert a given integer to a hex string that starts with the prefix 0x.

Example:

my_int = 2023
my_hex = hex(my_int)
print(my_hex)

Output:

0x7e7

Using the format() function with the x specifier is an alternative solution. However, it returns a hex string without the prefix 0x. You can simply add this prefix with string concatenation if needed.

Example:

# convert 2023 to hex without prefix
my_hex = format(2023, 'x')
# add prefix
my_hex = '0x' + my_hex
print(my_hex)

Output:

0x7e7

Convert a float to a hex string

In Python, in order to convert a float number to a hex string, the easiest and most convenient way is to use the float.hex() method. The resulting hex string has the form 0xh.hhhhp+e, where h.hhhh is the hexadecimal fraction, and e is the exponent in decimal.

Example:

my_float = 9.999
my_hex = my_float.hex()
print(my_hex)

Output:

0x1.3ff7ced916873p+3

That’s it. Happy coding & have a nice day. Goodbye!