简体   繁体   中英

Unpacking a list/string of hex values into integers

I'm trying to unapck a list from hex to integers in python.

So for example:

hexValues = '\x90\x82|uj\x82ix'
decodedHex = struct.unpack_from('B', hexValues,0)
print decodedHex

Which would print (144,) and nothing else. Is there any way I can loop through this string to get all values? (bear in mind the length of hex values is much longer than the example given.)

You can get all the values at once:

import struct

hexValues = '\x90\x82|uj\x82ix'
format = '%dB' % len(hexValues)
decodedHex = struct.unpack_from(format, hexValues)
print(decodedHex)  # -> (144, 130, 124, 117, 106, 130, 105, 120)

As Jon Clements helpfully pointed out in a comment, you don't really need to use the struct module:

decodedHex = tuple(bytearray(hexValues))
print(decodedHex)  # -> (144, 130, 124, 117, 106, 130, 105, 120)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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