“{:02x}”无法生成 239557639 的成对十六进制格式

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

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

我知道这种格式会成对生成十六进制。它也适用于另一个整数,但不适用于 239557639

实际上,我想对输出进行以下操作

>>> 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')
>>>

在这种情况下,您的十六进制数字格式可能存在问题。试试 {:08x}:

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

一个更通用的函数,用于为整数制作可打印的字节对齐的十六进制字符串:

def aligned_hex_string(number, align_by=2):
    length = len(format(number, 'x'))
    mod = length % align_by
    return format(number, '0{}x'.format(length + align_by - mod) if mod else 'x')

print(aligned_hex_string(13))
print(aligned_hex_string(255))
print(aligned_hex_string(256))
print(aligned_hex_string(239557639))
print(aligned_hex_string(239557, 4))

输出:

0d
ff
0100
0e475c07
0003a7c5