How to convert an int to a hex string?


Question

I want to take an integer (that will be <= 255), to a hex string representation

e.g.: I want to pass in 65 and get out '\x41', or 255 and get '\xff'.

I've tried doing this with the struct.pack('c',65), but that chokes on anything above 9 since it wants to take in a single character string.

1
192
7/22/2015 1:54:30 PM

Accepted Answer

You are looking for the chr function.

You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.

>>> chr(0x65) == '\x65'
True


>>> hex(65)
'0x41'
>>> chr(65) == '\x41'
True

Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.

197
2/16/2010 12:16:01 AM

This will convert an integer to a 2 digit hex string with the 0x prefix:

strHex = "0x%0.2X" % 255

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon