Nate Duong Nate Duong - 1 month ago 5
C++ Question

reading and convert binary data in C++

I am a new C++ guy, and working on the data collection.I have this code to read and print out data:

int main ()
{
string name;
ifstream input;
double vector_length;
vector_length = 14;

//Open the input file
input.open("data.txt",ios::out | ios::app | ios::binary );

vector<complex<double> > f(vector_length);

for(int i=0; i<vector_length;i++){
getline (input,name);
cout << name << endl;
istringstream is(name);
complex<double> c;
is >> c;
f[i] = complex<double>(c.real(), c.imag());
cout << "the complex number is " << c << "\n";
cout <<"real: " << c.real() << endl;
cout <<"image:" << c.imag() << endl;

}
for(int i=0; i < vector_length;i++){
cout <<i<<" "<< f[i]<<endl;
}

return 0;
}





and the data.txt look like:

(16,-144)
(-80,-64)
(-80,16)
(16,48)
(96,95)
(111,-32)
(64,-96)
(64,-16)
(31,-48)
(-96,-48)
(-32,79)
(16,48)
(-80,80)
(-48,128)





now, I want to do the same way, but get values from binary data
(input.open("data.bin",ios::out | ios::app | ios::binary );)
such as:

004038c0 e5 ff 32 00 e1 ff 13 00 00 00 00 00 f9 ff b0 ff |..2.............|
004038d0 e8 ff b2 ff de ff f3 ff c0 ff 06 00 b2 ff 18 00 |................|
004038e0 41 00 09 00 29 00 bc ff 9f ff f9 ff f8 ff 51 00 |A...).........Q.|
004038f0 0d 00 de ff b1 ff 18 00 c4 ff 26 00 19 00 bd ff |..........&.....|
00403900 10 00 fe ff 14 00 2e 00 d0 ff 05 00 8f ff fa ff |................|
00403910 44 00 2a 00 3b 00 c9 ff ed ff e2 ff f3 ff 21 00 |D.*.;.........!.|
00403920 0e 00 ef ff af ff f8 ff bf ff f6 ff 0b 00 ce ff |................|
00403930 03 00 20 00 11 00 0e 00 02 00 6f ff c9 ff c5 ff |.. .......o.....|
00403940 cf ff f5 ff d5 ff 94 ff d6 ff a3 ff 25 00 2c 00 |............%.,.|


which represent for complex data above.
(16,48)(-80,80)(-48,128)
....But I could not get the data print out.

Answer

The fact that you open std::ifstream with flag ios::binary only affects how OS handles reading. For example on MS Windows OS converts "\n\r" sequence to "\r" and "ctrl-z" to EOF for text files and not for binary. But that flag would not change operator>> to load binary data. You have to use std::ifstream::read() method to read binary data into memory:

double real = 0, imag = 0;
input.read( reinterpret_cast<char *>( &real ), sizeof( real ) );
input.read( reinterpret_cast<char *>( &imag ), sizeof( imag ) );
complex<double> c( real, imag );