pythonarraysshort

Converting bytearray to short int in python


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?


Solution

  • Using the struct module:

    import struct
    
    count = len(barray)/2
    integers = struct.unpack('H'*count, barray)
    

    Depending on the endianness you may want to prepend a < or > for the unpacking format. And depending on signed/unsigned, it's h, or H.