简体   繁体   English

C:读取二进制文件

[英]C : reading binary files

I don't normally work with binary files so I apologize if the answer to this is obvious. 我通常不使用二进制文件,因此如果答案很明显,我深表歉意。 I am able to read fine from a certain binary file using the following command: 我可以使用以下命令从某个二进制文件中正常读取:

nread = fread(&data[0],sizeof(float),maxpts,fptr);

The binaries are a standardized scientific format and it seems that the data is stored as floats. 二进制文件是一种标准化的科学格式,似乎数据存储为浮点数。 I would prefer to read this data into an array of type double however, and when I try to simply switch the type of data to double (from float), and leave sizeof(float) the same, it doesn't retrieve my data correctly. 我更喜欢将数据读取到double类型的数组中,当我尝试简单地将数据类型切换为double类型(从float),并保持sizeof(float)不变时,它无法正确检索我的数据。 How would I go about doing this? 我将如何去做呢? Thanks, Zach. 谢谢,扎克。

You will need to read the data as floats and convert it to doubles by bulk assignment (eg, read into an array of floats, have a separate array of doubles, and, for each element, set doubleArray[i] = floatArray[i] ). 您将需要将数据读取为float并通过批量分配将其转换为double(例如,读入float数组,拥有单独的double数组,并为每个元素设置doubleArray[i] = floatArray[i] )。

There are ways that you could accelerate this process (by making use of specific facts about the storage of floats and doubles), but it's probably not worth it, especially as it may introduce subtle inaccuracies. 有多种方法可以加快此过程(通过使用有关浮点数和双精度数存储的特定事实),但是这可能不值得,尤其是因为它可能会引入一些细微的错误。

You could read the data in as float precision, then allocate an array of doubles and then manually fill the array of doubles using a for loop. 您可以以float精度读取数据,然后分配双精度数组,然后使用for循环手动填充双精度数组。

See one of my old questions How can I perform conversion from float -> double -> float when processing an audio buffer in c++ 看到我的一个古老的问题之一, 在C ++中处理音频缓冲区时,如何从float-> double-> float进行转换

Basically . 基本上。 .

doubleArray=malloc(numElements*sizeof(double));
for (int nn=0; nn<numElements; ++nn)
{
    doubleArray[nn] = floatArray[nn];
}

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

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