Home > front end >  How to split a bytearray or a bytes object into 16-bit integers?
How to split a bytearray or a bytes object into 16-bit integers?

Time:10-12

Given a bytearray object of length 2xN, how can I get a list (or an array) of N 16-bit integers from that object?

For example, if ba is defined as:

ba = bytearray([0x01, 0x02, 0x01, 0x03, 0xff, 0xff])

Then after conversion, the result shall be like:

ia = [0x0102, 0x0103, 0xffff]
print(ia[1]) ==> 0x0103

CodePudding user response:

You can use int.from_bytes and a little list comprehension. Please note that byte_order needs to be specified, so you might have to change that depending on your application.

ba = bytearray([0x01, 0x02, 0x01, 0x03, 0xff, 0xff])
ia = [int.from_bytes(ba[i:i 2], "big") for i in range(0, len(ba), 2)]

CodePudding user response:

That looks like a big endian encoding (the first byte is the high bits). You can use the struct package. It uses a format string to describe the bytes coming from some iterable.

import struct
unpacker = struct.Struct(">H")
ba = bytearray([0x01, 0x02, 0x01, 0x03, 0xff, 0xff])
result =  [unpacked[0] for unpacked in unpacker.iter_unpack(ba)]
print([hex(r) for r in result])
  • Related