How to convert an int to a hex string? How to convert an int to a hex string? python python

How to convert an int to a hex string?


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.


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

strHex = "0x%0.2X" % 255


What about hex()?

hex(255)  # 0xff

If you really want to have \ in front you can do:

print '\\' + hex(255)[1:]


matomo