I have a long bytearray
barray=b'\x00\xfe\x4b\x00...
What would be the best way to convert it to a list of 2-byte integers?
You can use the struct
package for that:
from struct import unpack
tuple_of_shorts = unpack('h'*(len(barray)//2),barray)
This will produce signed shorts. For unsigned ones, use 'H'
instead:
tuple_of_shorts = unpack('H'*(len(barray)//2),barray)
This produces on a little-endian machine for your sample input:
>>> struct.unpack('h'*(len(barray)//2),barray)
(-512, 75)
>>> struct.unpack('H'*(len(barray)//2),barray)
(65024, 75)
In case you want to work with big endian, or little endian, you can put a >
(big endian) or <
(little endian) in the specifications. For instance:
# Big endian
tuple_of_shorts = unpack('>'+'H'*(len(barray)//2),barray) # unsigned
tuple_of_shorts = unpack('>'+'h'*(len(barray)//2),barray) # signed
# Little endian
tuple_of_shorts = unpack('<'+'H'*(len(barray)//2),barray) # unsigned
tuple_of_shorts = unpack('<'+'h'*(len(barray)//2),barray) # signed
Generating:
>>> unpack('>'+'H'*(len(barray)//2),barray) # big endian, unsigned
(254, 19200)
>>> unpack('>'+'h'*(len(barray)//2),barray) # big endian, signed
(254, 19200)
>>> unpack('<'+'H'*(len(barray)//2),barray) # little endian, unsigned
(65024, 75)
>>> unpack('<'+'h'*(len(barray)//2),barray) # little endian, signed
(-512, 75)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With