将小端字符串转换为整数 [英] Convert little endian string to integer

查看:36
本文介绍了将小端字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 wave 模块从 wave 文件中读取了样本,但它将样本作为字符串提供,它不在 wave 中,因此它是小端(例如,\x00).

将其转换为 python 整数或 numpy.int16 类型的最简单方法是什么?(它最终会变成一个 numpy.int16,所以直接去那里没问题).

代码需要在小端和大端处理器上工作.

解决方案

struct 模块将打包数据转换为 Python 值,反之亦然.

<预><代码>>>>导入结构>>>struct.unpack("<h", "\x00\x05")(1280,)>>>struct.unpack("<h", "\x00\x06")(1536,)>>>struct.unpack("<h", "\x01\x06")(1537,)

"h" 表示短整数,或 16 位整数.<"表示使用小端.

I have read samples out of a wave file using the wave module, but it gives the samples as a string, it's out of wave so it's little endian (for example, \x00).

What is the easiest way to convert this into a python integer, or a numpy.int16 type? (It will eventually become a numpy.int16, so going directly there is fine).

Code needs to work on little endian and big endian processors.

解决方案

The struct module converts packed data to Python values, and vice-versa.

>>> import struct
>>> struct.unpack("<h", "\x00\x05")
(1280,)
>>> struct.unpack("<h", "\x00\x06")
(1536,)
>>> struct.unpack("<h", "\x01\x06")
(1537,)

"h" means a short int, or 16-bit int. "<" means use little-endian.

这篇关于将小端字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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