简体   繁体   English

蟒蛇; 结构; 24位整数的重复计数

[英]python; struct; repeat count for 24-bit integers

I want to unpack array of 2760 bytes, to new array of 920 24-bit integers. 我想将2760字节的数组解压缩为920个24位整数的新数组。 Unlike eg 16 bit integers, where would struct.unpack_from('920h',array,0) do the thing, you can't use 'repeat count' syntax with 24 bit integers: 与16位整数不同,在struct.unpack_from('920h',array,0)做事情的地方,您不能对24位整数使用“重复计数”语法:

struct.unpack_from('920<i', array,0 )

This gives the following error: 'bad count in struct format'. 这将产生以下错误:“结构格式的错误计数”。

So what's the syntax for 24 bit integers? 那么24位整数的语法是什么? I can't find anything in the documentation. 我在文档中找不到任何内容。

struct does not natively support 24-bit integers. struct本机不支持24位整数。

If these are unsigned integers, on trick you could use is to use the array.array() type to read the data as bytes, then process these per 3: 如果这些是无符号整数,则可以使用的技巧是使用array.array()类型以字节为单位读取数据,然后按3进行处理:

import array

b = array.array('B', yourdata)
result = [b[i] << 16 | b[i + 1] << 8 | b[i + 2] for i in xrange(0, len(b), 3)]

or you could use array.fromfile() to read the data from a file input as needed: 或者您可以根据需要使用array.fromfile()从文件输入中读取数据:

with open('somefilename', 'rb') as infh:
    b = array.array('B')
    b.fromfile(infh, 920)
    result = [b[i] << 16 | b[i + 1] << 8 | b[i + 2] for i in xrange(0, len(b), 3)]

Adjust as needed for byte order (swap the b[i] and b[i + 2] references). 根据需要调整字节顺序(交换b[i]b[i + 2]引用)。

If these are signed 24-bit integers, you may have to stick to struct , and pad the least significant side with a null-byte, then right-shift the result by 8. That way you don't have to worry about negative vs. positive numbers and how to pad either type on the most-significant side: 如果这些是带符号的 24位整数,则可能必须坚持struct ,并用空字节填充最低有效位 ,然后将结果右移8。这样,您就不必担心负数与。正数以及如何在最重要的一面填充两种类型:

[struct.unpack('>i', yourdata[i:i+3] + '\x00')[0] >> 8
 for i in range(0, len(yourdata), 3)]

for big-endian, and 对于大端,和

[struct.unpack('<i', '\x00' + yourdata[i:i+3])[0] >> 8
 for i in range(0, len(yourdata), 3)]

for little-endian signed 24-bit integers. 小尾数有符号24位整数。

If you are using Python 3.2 or newer, you can read the data 3 bytes at a time and convert to integers with int.from_bytes() , which gives you more flexibility over endianess and if you are parsing signed or unsigned integers. 如果您使用的是Python 3.2或更高版本,则可以一次读取3个字节的数据,并使用int.from_bytes()转换为整数,这使您可以更加灵活地处理字节序以及解析有符号或无符号整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM