uint8 little endian array to uint16 big endian

╄→гoц情女王★ 提交于 2019-12-24 01:17:45

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/51030163/uint8-little-endian-array-to-uint16-big-endian

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!