Search code examples
pythonpython-3.xhexnumber-formatting

"{:02x}" can't results pairwise hex format for 239557639


  >>> "{:02x}".format(13)
     '0d'
  >>> "{:02x}".format(239557639)
    'e475c07'

I know this format result the hex in pair wise. It also works for another integer but not works for 239557639

Actually, I want to do following with the output

>>> bytearray.fromhex('e475c07')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: non-hexadecimal number found in fromhex() arg at position 7
>>> bytearray.fromhex('0e475c07')
bytearray(b'\x0eG\\\x07')
>>>

Solution

  • In this case, it might be an issue with your hex number formatting. Try {:08x}:

    >>> bytearray.fromhex('{:08x}'.format(239557639))
    bytearray(b'\x0eG\\\x07')