AndroidDev
AndroidDev

Reputation: 21237

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

Upvotes: 42

Views: 141602

Answers (7)

emersonblima
emersonblima

Reputation: 61

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

Upvotes: 2

MatrixManAtYrService
MatrixManAtYrService

Reputation: 9191

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.

Upvotes: 13

vitperov
vitperov

Reputation: 1407

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

Upvotes: 6

pepr
pepr

Reputation: 20794

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'

Upvotes: 4

Diego Queiroz
Diego Queiroz

Reputation: 3411

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.

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 602365

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

Upvotes: 69

JBernardo
JBernardo

Reputation: 33407

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

Upvotes: 22

Related Questions