I'm sure this must be a common problem but can't seem to find an equivalent question* or example.
I have a binary file that is a series of 4 byte floats. I am reading into a vector that is sized by the length of the file (divided by the size of my float). I have used the bytesToFloat method from another post. When printing out the data my code returns the same value for all data points. What's wrong?
*Sorry to the admins if I have missed it.
#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;
}