如何使用Python从24位和小端文件中读取整数? [英] How to read integers from a file that are 24bit and little endian using Python?

查看:1001
本文介绍了如何使用Python从24位和小端文件中读取整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法来读取这些整数?我更喜欢内置的方法,但我认为它可以做一些操作。

干杯



编辑

我想到了另外一种方法来做到这一点,这与以下的方式是不同的,在我看来更清晰。它的另一端用零填充,然后移动结果。没有,如果需要,因为移动填充任何MSB是最初。

  struct.unpack('< i','\ 0'+字节)[0]>> 8 


解决方案 code>模块允许您将字节解释为不同类型的数据结构,并控制字节顺序。



如果从文件读取单个三字节数字,你可以这样转换它:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ struct $'$'$'$'$'$' $ b

模块不支持24位字,因此'\\ \\ 0' -padding。



编辑:签名的数字更复杂。您可以复制高位,并将高位设置为零,因为它移动到4个字节的最高位置(最后一个 \xff ):

  struct.unpack('< i',bytes +('\0'if bytes [2]<'\\ \\ x80'else'\xff'))

或者,对于python3( bytes 是保留字,检查字节数组的字节给出 int ):

pre $ struct.unpack('< i',chunk +('\0'if chunk [2]< 128 else'\xff'))


Is there an easy way to read these integers in? I'd prefer a built in method, but I assume it is possible to do with some bit operations.
Cheers

edit
I thought of another way to do it that is different to the ways below and in my opinion is clearer. It pads with zeros at the other end, then shifts the result. No if required because shifting fills with whatever the msb is initially.

struct.unpack('<i','\0'+ bytes)[0] >> 8

解决方案

Python's struct module lets you interpret bytes as different kinds of data structure, with control over endianness.

If you read a single three-byte number from the file, you can convert it thus:

struct.unpack('<I', bytes + '\0')

The module doesn't appear to support 24-bit words, hence the '\0'-padding.

EDIT: Signed numbers are trickier. You can copy the high-bit, and set the high bit to zero because it moves to the highest place of 4 bytes (the last \xff has it).:

struct.unpack('<i', bytes + ('\0' if bytes[2] < '\x80' else '\xff'))

Or, for python3 (bytes is a reserved word, checking a byte of a byte array gives an int):

struct.unpack('<i', chunk + ('\0' if chunk[2] < 128 else '\xff'))

这篇关于如何使用Python从24位和小端文件中读取整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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