如何 unpack/decode 十六进制字节中的十六进制字符串?

How to unpack/decode hex string in hex bytes?

我正在尝试 unpack/decode 二进制字符串,如下所示:

hex_string = '\x00\x00\x01p\x89 \x01\x89\x00\x00\x01p\x80 \x01\x89\t\x89oPIE'

这是我当前的代码:

>>> from struct import unpack
>>> hex_string = '\x00\x00\x01p\x80 \x01\x89\x00\x00\x01p\x80 \x01\x89\t\x89oPIE'
>>> unpack('d', hex_string)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: unpack requires a string argument of length 8
>>> hex_string.decode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found

我要找的输出是这样的:

'00 00 01 70 89 20 01 89 09 89 6F 50 49 45'

我怎样才能做到这一点?谢谢

您可以使用 str.format() 来完成任务:

hex_string = '\x00\x00\x01p\x89 \x01\x89\x00\x00\x01p\x80 \x01\x89\t\x89oPIE'

print(*['{:02x}'.format(ord(ch)) for ch in hex_string], sep=' ')

打印:

00 00 01 70 89 20 01 89 00 00 01 70 80 20 01 89 09 89 6f 50 49 45

编辑:要列出输出,您可以使用:

hex_strings = [
    '\x00\x00\x01p\x89 \x01\x89\x00\x00\x01p\x80 \x01\x89\t\x89oPIA',
    '\x01\x00\x01p\x89 \x01\x89\x00\x00\x01p\x80 \x01\x89\t\x89oPIB',
    '\x02\x00\x01p\x89 \x01\x89\x00\x00\x01p\x80 \x01\x89\t\x89oPIC'
]

def get_hex_string(s):
    return ' '.join('{:02x}'.format(ord(ch)) for ch in s)

out = [get_hex_string(hs) for hs in hex_strings]

print(out)

打印:

['00 00 01 70 89 20 01 89 00 00 01 70 80 20 01 89 09 89 6f 50 49 41', '01 00 01 70 89 20 01 89 00 00 01 70 80 20 01 89 09 89 6f 50 49 42', '02 00 01 70 89 20 01 89 00 00 01 70 80 20 01 89 09 89 6f 50 49 43']