简体   繁体   中英

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

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:]

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() .

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:] )

htmlColor = "#%02X%02X%02X" % (red, green, blue)

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

>>> import binascii
>>> binascii.hexlify('abc\n')
'6162630a'

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM