Paul G.
Paul G.

Reputation: 479

uint8 little endian array to uint16 big endian

In Python2.7, from an USB bulk transfer I get an image frame from a camera:

frame = dev.read(0x81, 0x2B6B0, 1000)

I know that one frame is 342x260 = 88920 pixels little endian, because that I read 2x88920 = 177840 (0x2B6B0) from the bulk transfer.

How can I convert the content of the frame array that is typecode=B into an uint16 big endian array?

Upvotes: 2

Views: 1275

Answers (1)

Ondrej K.
Ondrej K.

Reputation: 9679

Something like this should do the trick:

frame_short_swapped = array.array('H', ((j << 8) | i
                                        for (i,j)
                                        in zip(frame[::2], frame[1::2])))

It pairs two consecutive bytes from frame and unpacks that pair into i and j. Shift j one byte left and or it with i, effectively swap bytes (aka endianness conversion for 2 byte type) and feed that into an H type array. I am a bit uneasy about that bit, since it should correspond to C short type (according to docs), but type sizes really only guarantee minimal length. I guess you would need to introduce ctypes.c_uint16 if strict about that?

Upvotes: 1

Related Questions