visual c++ - Building 32bit Float from 4 Bytes [Binary File I/O] in C++ -



visual c++ - Building 32bit Float from 4 Bytes [Binary File I/O] in C++ -

i'm sure must mutual problem can't seem find equivalent question* or example.

i have binary file series of 4 byte floats. reading vector sized length of file (divided size of float). have used bytestofloat method another post. when printing out info code returns same value info points. what's wrong?

*sorry admins if 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 programme file.close(); homecoming 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; homecoming output; }

so bit of effort , igor's comment able solve problem. next function reads buffer vector.

vector<char> buffer; void fill() { string filename = ""; cout << "please come in 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,'\0'); length-=540; buffer.resize(length); file.read(&buffer[0],length); } }

then later on phone call bytestofloat in loop. endian-ness of bytestofloat wrong has been reversed , outputs same values original file (i made random file generator output plain text version comparison).

visual-c++ file-io binaryfiles

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -