uint8小字节序到uint16大字节序 [英] uint8 little endian array to uint16 big endian

查看:475
本文介绍了uint8小字节序到uint16大字节序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python2.7中,通过USB批量传输,我从相机获得了图像帧:

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

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

我知道一帧是342x260 = 88920像素的小尾数,因为我从批量传输中读取了2x88920 = 177840(0x2B6B0).

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

如何将typecode = B的帧数组的内容转换为uint16大字节序数组?

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

推荐答案

这种方法应该可以解决问题:

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])))

它将来自frame的两个连续字节配对,并将其解压缩为ij.将j左移一个字节,并用i将其移至or,有效地交换字节(2字节类型的aka字节顺序转换)并将其输入到H类型的数组中.我对此有点不安,因为它应该对应于C short类型(根据文档),但是类型大小实际上只能保证最小长度.我想如果需要严格的话,您需要引入ctypes.c_uint16吗?

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?

这篇关于uint8小字节序到uint16大字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆