简体   繁体   English

如何在Python中读取具有32位浮点数,64位浮点数和另一个32位浮点数的二进制文件

[英]How to read a binary file with a 32-bit float, a 64-bit float and another-32 bit float in Python

This is a binary file with a very simple structure for learning purposes. 这是一个二进制文件,具有用于学习目的的非常简单的结构。 Each register has 3 numbers: a 32-bit float, a 64-bit float and another 32-bit float. 每个寄存器具有3个数字:一个32位浮点数,一个64位浮点数和另一个32位浮点数。 If I dump it on the screen in hexadecimal, it looks like this: 如果我以十六进制的形式将其转储到屏幕上,则如下所示:

0000000: 0800 0000 0000 0000 0000 0000 0800 0000  ................
0000010: 0800 0000 0000 0000 0000 f03f 0800 0000  ...........?....
0000020: 0800 0000 182d 4454 fb21 0940 0800 0000  .....-DT.!.@....

(...) (......)

If I manually copy the third line in binary format, I can read it into three variables: 如果我以二进制格式手动复制第三行,则可以将其读取为三个变量:

import struct
data = b'\x08\x00\x00\x00\x18-DT\xfb!\t@\x08\x00\x00\x00'
l1, value, l2 = struct.unpack("<idi", data)
# (8, 3.141592653589793, 8)

That works, but I need to read the file from disk, not only manually copying each register in binary, because I need to do this with millions data. 那行得通,但是我需要从磁盘读取文件,不仅要手动复制二进制的每个寄存器,因为我需要处理数百万个数据。 I need something equivalent to the following command used in ascii files: 我需要与在ascii文件中使用的以下命令等效的命令:

l1, value, l2 = pylab.loadtxt('./test_file.binary',unpack=True)

Which doesn't work here. 这在这里不起作用。

Read the file in binary mode: 以二进制模式读取文件:

def read_stuff(fname='test_file.binary'):
    with open(fname, mode='rb') as f:
        while True:
            data = f.read(16)
            if len(data) < 16:
                # end of file
                return
            yield struct.unpack("<idi", data)

This is a generator. 这是一个发电机。 To consume it: 消费它:

for l1, value, l2 in read_stuff():
    ...

You may try this method 您可以尝试此方法

# includes core parts of numpy, matplotlib
import matplotlib.pyplot as plt
import numpy as np
# include scipy's signal processing functions
import scipy.signal as signal


# practice reading in complex values stored in a file
# Read in data that has been stored as raw I/Q interleaved 32-bit float samples
dat = np.fromfile("iqsamples.float32", dtype="float32")
# Look at the data. Is it complex?


dat = dat[0::2] + 1j*dat[1::2]
print(type(dat))
print(dat)

# # Plot the spectogram of this data
plt.specgram(dat, NFFT=1024, Fs=1000000)
plt.title("PSD of 'signal' loaded from file")
plt.xlabel("Time")
plt.ylabel("Frequency")
plt.show()  # if you've done this right, you should see a fun surprise here!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM