简体   繁体   English

如何以Python方式在MatLab中解压缩二进制数据

[英]How to unpack binary data in MatLab the Python way

Python has a way to read blocks of binary data and then unpack them from their original encoding into a more accessible form. Python可以读取二进制数据块,然后将其从原始编码中解压缩为更易于访问的形式。 For example, in some Python code I am using, I use the following code to accomplish this: 例如,在我正在使用的某些Python代码中,我使用以下代码来完成此操作:

    with open(filename, "rb") as binary_file:
        # Read many records at once
        data = binary_file.read(number_of_records*record_size)

    fmt = "8B Q Q 2L 2L 2L 4H 4H 3H2B"
    self.data_array = np.asarray(list(struct.iter_unpack("< " + fmt, data)))

I'd like to know how to do this in Matlab in the same efficient way, without having to read each variable individually. 我想知道如何在Matlab中以相同有效的方式执行此操作,而不必分别读取每个变量。

Is there something in Matlab to do this? Matlab中有什么可以做的吗?

One way to do this is to read the data using fread and then convert using typecast . 一种方法是使用fread读取数据,然后使用typecast进行typecast I'm not familiar with the format you used, but say you have a collection of integers and floats. 我不熟悉您使用的格式,但是说您有整数和浮点数的集合。 You can read them as one large collection of bytes and then covert. 您可以将它们读取为一个大的字节集合,然后隐蔽读取。

fid = fopen('file.bin', 'rb');
data = fread(fid, 32, '*uint8');
ints = typecast(data(1:8), 'int32');
floats = typecast(data(9:end), 'single');

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

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