我確定這肯定是一個常見問題,但似乎無法找到等價的問題*或示例。從C++中的4字節[二進制文件I/O]構建32位浮點數
我有一個二進制文件,是一系列4字節的浮點數。我讀入一個由文件長度決定的矢量(除以我的浮點數)。我使用了another post的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;
}
如果你放棄所有這些循環,並執行'file.read(&data [0],size);'(在調整resize'之後)會發生什麼?當你處於這個狀態時,使'size'成爲一個整數。另外,你怎麼知道你的文件不**實際上包含相同值的副本? – 2014-10-11 01:10:32
我嘗試了file.read方法,它只輸出十六進制值而不是浮點本身。這就是爲什麼我試圖重新構造它的單個字節的浮點數。 我在Visual Studio中打開文件,並且十六進制值不同。它也是從我寫的另一段代碼中隨機生成的,它生成一系列隨機的浮點數(並且已經檢查了該程序的輸出)。 – 2014-10-13 08:51:51
你是什麼意思,「它只輸出」? 'read'不輸出任何內容。 – 2014-10-13 15:15:19