繁体   English   中英

如何以十六进制字节解压/解码十六进制字符串?

[英]How to unpack/decode hex string in hex bytes?

我正在尝试解压缩/解码如下所示的二进制字符串:

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

我正在寻找的 output 是这样的:

'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

编辑:要列出 output,您可以使用以下命令:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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