How can I format an integer to a two digit hex?

Question:

Does anyone know how to get a chr to hex conversion where the output is always two digits?

for example, if my conversion yields 0x1, I need to convert that to 0x01, since I am concatenating a long hex string.

The code that I am using is:

hexStr += hex(ord(byteStr[i]))[2:]
Asked By: AndroidDev

||

Answers:

You can use the format function:

>>> format(10, '02x')
'0a'

You won’t need to remove the 0x part with that (like you did with the [2:])

Answered By: JBernardo

You can use string formatting for this purpose:

>>> "0x{:02x}".format(13)
'0x0d'

>>> "0x{:02x}".format(131)
'0x83'

Edit: Your code suggests that you are trying to convert a string to a hexstring representation. There is a much easier way to do this (Python2.x):

>>> "abcd".encode("hex")
'61626364'

An alternative (that also works in Python 3.x) is the function binascii.hexlify().

Answered By: Sven Marnach

Use format instead of using the hex function:

>>> mychar = ord('a')
>>> hexstring = '%.2X' % mychar

You can also change the number “2” to the number of digits you want, and the “X” to “x” to choose between upper and lowercase representation of the hex alphanumeric digits.

By many, this is considered the old %-style formatting in Python, but I like it because the format string syntax is the same used by other languages, like C and Java.

Answered By: Diego Queiroz

The standard module binascii may also be the answer, namely when you need to convert a longer string:

>>> import binascii
>>> binascii.hexlify('abcn')
'6162630a'
Answered By: pepr
htmlColor = "#%02X%02X%02X" % (red, green, blue)
Answered By: vitperov

The simpliest way (I think) is:

your_str = '0x%02X' % 10
print(your_str)

will print:

0x0A

The number after the % will be converted to hex inside the string, I think it’s clear this way and from people that came from a C background (like me) feels more like home

Answered By: emersonblima

If you’re using python 3.6 or higher you can also use fstrings:

v = 10
s = f"0x{v:02x}"
print(s)

output:

0x0a

The syntax for the braces part is identical to string.format(), except you use the variable’s name. See https://www.python.org/dev/peps/pep-0498/ for more.

Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.