12

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

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

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

4

4 回答 4

20

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

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

“h”表示一个短整数或 16 位整数。“<”表示使用小端。

于 2009-11-08T21:51:28.383 回答
12

struct如果您必须将一个或少量的 2 字节字符串转换为整数,这很好,但arraynumpy本身是更好的选择。具体来说,numpy.fromstring(使用适当的dtype参数调用)可以直接将字节从您的字符串转换为(无论是什么)的数组dtype。(如果numpy.little_endian为假,那么您将不得不交换字节——更多讨论请参见此处,但基本上您需要byteswap在刚刚构建的数组对象上调用该方法fromstring)。

于 2009-11-08T22:34:44.057 回答
1

当您的二进制字符串表示单个短整数时, Kevin Burke对这个问题的回答非常有效,但如果您的字符串包含表示多个整数的二进制数据,则您需要为字符串表示的每个额外整数添加一个额外的“h”。

对于 Python 2

转换代表2 个整数的 Little Endian 字符串

import struct
iValues = struct.unpack("<hh", "\x00\x04\x01\x05")
print(iValues)

输出:(1024、1281)

转换代表3 个整数的 Little Endian 字符串

import struct
iValues = struct.unpack("<hhh", "\x00\x04\x01\x05\x03\x04")
print(iValues)

输出:(1024、1281、1027)

显然,总是猜测需要多少个“h”字符是不现实的,所以:

import struct

# A string that holds some unknown quantity of integers in binary form
strBinary_Values = "\x00\x04\x01\x05\x03\x04"

# Calculate the number of integers that are represented by binary string data
iQty_of_Values = len(strBinary_Values)/2

# Produce the string of required "h" values
h = "h" * int(iQty_of_Values)

iValues = struct.unpack("<"+h, strBinary_Values)
print(iValues)

输出:(1024、1281、1027)

对于 Python 3

import struct

# A string that holds some unknown quantity of integers in binary form
strBinary_Values = "\x00\x04\x01\x05\x03\x04"

# Calculate the number of integers that are represented by binary string data
iQty_of_Values = len(strBinary_Values)/2

# Produce the string of required "h" values
h = "h" * int(iQty_of_Values)

iValues = struct.unpack("<"+h, bytes(strBinary_Values, "utf8"))
print(iValues)

输出:(1024、1281、1027)

于 2018-12-26T02:18:14.913 回答
0
int(value[::-1].hex(), 16)

举例:

value = b'\xfd\xff\x00\x00\x00\x00\x00\x00'
print(int(value[::-1].hex(), 16))
65533

[::-1]反转值(小端),.hex()将 trabnsform 转换为十六进制文字,int(,16)从十六进制文字转换为 int base16。

于 2020-11-02T00:51:21.283 回答