在C++中从4字节[二进制文件I/O]构建32位浮点



我确信这一定是一个常见问题,但似乎找不到等效的问题*或示例。

我有一个二进制文件,它是一系列4字节的浮点值。我正在读取一个向量,该向量的大小由文件的长度(除以浮点值的大小)决定。我使用了另一篇文章中的bytesToFloat方法。当打印出数据时,我的代码为所有数据点返回相同的值。怎么了?

*如果我错过了,对不起管理员。

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
typedef unsigned char uchar;
float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3);
int main()
{
int i,j;
char u[4];
// Open  file
ifstream file;
file.open("file.dat");
// Find file size in bytes
file.seekg(0,ios::end);
double size = 0;
size = file.tellg();
file.seekg(0,ios::beg);
vector<float> data;
data.resize(size/4);
i=0;
while(i<size/4)
{
    j=0;
    while(j<4)
    {
        file.read(&u[j],1);
        j++;
    }
    data[i] = bytesToFloat(u[0],u[1],u[2],u[3]);
    cout << data[i]<< endl;
    i++;
}
// End program
file.close();
return 0;
}
float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3)
{
float output;
*((uchar*)(&output) + 3) = b0;
*((uchar*)(&output) + 2) = b1;
*((uchar*)(&output) + 1) = b2;
*((uchar*)(&output) + 0) = b3;
return output;
}

因此,经过一点努力和Igor的评论,我能够解决这个问题。下面的函数将所有内容读取到缓冲区向量中。

vector<char> buffer;
void fill() {
string filename = "";
cout << "Please enter a filename:n>";
getline(cin, filename);
ifstream file(filename.c_str());
if (file) {
    file.seekg(0,std::ios::end);
    streampos length = file.tellg();
    cout<< length << endl;
    file.seekg(0,std::ios::beg);
    file.seekg(540,'');
    length-=540;
    buffer.resize(length);
    file.read(&buffer[0],length);
}
}

稍后,我在循环中调用bytesToFloat。bytesToFloat的endian-ness不正确,因此现在已经反转,它输出的值与我的原始文件相同(我让我的随机文件生成器输出纯文本版本进行比较)。

最新更新