Tianyi Shen Tianyi Shen - 1 month ago 30
Python Question

Pack hex string using python struct

I want to pack a hex string with python pack.
Here is my code:

import struct
query='430401005001'
q= ('%x' % int(query, 16)).decode('hex').decode('utf-8')
qpacked=struct.pack('6s',str(q))


Query is a hex string.
The code does not work if I change the string to '53040600d0010100' and change 6s to 8s.
Is there any better way to pack such a hex string?

Answer

The string gets truncated because you're telling it you want to pack it up to length 6 (6s). You'll have to either raise that number, or work around your string getting truncated.

Also, stop juggling with the encoding of your string, just query.decode('hex') should suffice.