快速反转二进制文件中 float32 字节顺序的方法
Fast way to reverse float32 endianness in binary file
我有一个二进制文件,大小有几百MB。它包含 float32 big-endian 格式的样本(每个样本 4 个字节)。我想将它们转换为小端格式。一些背景:我想稍后将它们写入一个 .wav 文件,并且需要 little-endian 格式的数据 afaik。
下面的代码是我目前使用的。它似乎工作正常,但速度很慢(我假设是因为我一次只写 4 个字节):
import struct
infile = "infile_big_endian.raw"
outfile = "outfile_little_endian.raw"
with open(infile, "rb") as old, open(outfile , "wb") as new:
for chunk in iter(lambda: old.read(4), b""):
chunk = struct.pack("<f", struct.unpack(">f", chunk)[0])
new.write(chunk)
在 python 中有更快的方法吗?
NumPy 可能更快:
numpy.memmap(infile, dtype=numpy.int32).byteswap().tofile(outfile)
或覆盖输入文件:
numpy.memmap(infile, dtype=numpy.int32).byteswap(inplace=True).flush()
我们memory-map数组并使用byteswap
以C速度反转字节顺序。我使用 int32
而不是 float32
以防万一 NaN 可能是 float32
的问题。
我有一个二进制文件,大小有几百MB。它包含 float32 big-endian 格式的样本(每个样本 4 个字节)。我想将它们转换为小端格式。一些背景:我想稍后将它们写入一个 .wav 文件,并且需要 little-endian 格式的数据 afaik。
下面的代码是我目前使用的。它似乎工作正常,但速度很慢(我假设是因为我一次只写 4 个字节):
import struct
infile = "infile_big_endian.raw"
outfile = "outfile_little_endian.raw"
with open(infile, "rb") as old, open(outfile , "wb") as new:
for chunk in iter(lambda: old.read(4), b""):
chunk = struct.pack("<f", struct.unpack(">f", chunk)[0])
new.write(chunk)
在 python 中有更快的方法吗?
NumPy 可能更快:
numpy.memmap(infile, dtype=numpy.int32).byteswap().tofile(outfile)
或覆盖输入文件:
numpy.memmap(infile, dtype=numpy.int32).byteswap(inplace=True).flush()
我们memory-map数组并使用byteswap
以C速度反转字节顺序。我使用 int32
而不是 float32
以防万一 NaN 可能是 float32
的问题。