将小端字符串转换为整数
我用wave模块从一个波形文件中读取了样本,但它给出的样本是字符串格式,而且是小端格式(比如,\x00
)。
有没有简单的方法把这个转换成Python的整数,或者numpy.int16类型?(最终会变成numpy.int16,所以直接转换成这个也可以)。
代码需要在小端和大端的处理器上都能运行。
4 个回答
1
Kevin Burke的回答对于你的二进制字符串只表示一个短整数的情况非常有效,但如果你的字符串包含多个整数的二进制数据,你就需要为每个额外的整数添加一个'h'。
对于Python 2
将表示2个整数的小端字符串转换为整数
import struct
iValues = struct.unpack("<hh", "\x00\x04\x01\x05")
print(iValues)
输出: (1024, 1281)
将表示3个整数的小端字符串转换为整数
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)
12
struct
模块在你需要把一两个2字节的字符串转换成整数时是可以用的,但如果你要处理更多的数据,使用array
或者直接用numpy
会更好。具体来说,numpy.fromstring这个函数(记得传入合适的dtype
参数)可以直接把你的字符串中的字节转换成一个数组,数组的类型就是你指定的dtype
。如果numpy.little_endian
是假的话,你就需要交换字节顺序——想了解更多可以看这里,简单来说,你需要在用fromstring
创建的数组对象上调用byteswap
方法。
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位的整数。"<"表示使用小端字节序。