Ger Cas
Ger Cas

Reputation: 2308

How to unpack/decode hex string in hex bytes?

I'm trying to unpack/decode a binary string that looks like this:

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

This is my current code:

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

and the output I´m looking for is like this:

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

How can I accomplish this? Thanks

Upvotes: 2

Views: 600

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195583

You can use str.format() for the task:

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

Prints:

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

EDIT: To get the output to list, you can use this:

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)

Prints:

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

Upvotes: 2

Related Questions