I am trying to create a binary package out of some custom struct (or class). I created the binary package using std::stringstream class in c++. Then, I restore it from the stream to validate the binary package. It seems fine with 'unsinged int' or 'long long' data type. But, when it comes to floating numbers ('float' or 'double'), I couldn't restore it in full precision.
Here is the simple code I've used for the test.
#include <iostream>
#include <string>
void main() {
unsigned int idata = 1234;
long long lldata = 123123123;
double ddata = 343298374.123456789012345;
float fdata = 234324.1234567;
std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary);
// write data
ss.write(reinterpret_cast<const char*>(&idata), sizeof(unsigned int)); // 4 bytes
ss.write(reinterpret_cast<const char*>(&lldata), sizeof(long long)); // 8 bytes
ss.write(reinterpret_cast<const char*>(&ddata), sizeof(double)); // 8 bytes
ss.write(reinterpret_cast<const char*>(&fdata), sizeof(float)); // 4 bytes
// check buffer size
ss.seekp(0, std::ios::end);
std::cout << "buffered: " << ss.tellp() << " bytes\n"; // expect 24 bytes
// validate the stream
unsigned int c_idata;
long long c_lldata;
double c_ddata;
float c_fdata;
ss.seekg(0);
ss.read(reinterpret_cast<char*>(&c_idata), sizeof(unsigned int));
ss.read(reinterpret_cast<char*>(&c_lldata), sizeof(long long));
ss.read(reinterpret_cast<char*>(&c_ddata), sizeof(double));
ss.read(reinterpret_cast<char*>(&c_fdata), sizeof(float));
std::cout << "unsigned long: " << c_idata << std::endl;
std::cout << "long long: " << c_lldata << std::endl;
printf("double: %.*lf\n", 12, c_ddata);
printf("float: %.*f\n", 12, c_fdata);
}
I expect the binary stream size would be 24 bytes and I could restore all numbers without any loss of information. However, I couldn't restore the double and float number with full precision.
Here is the output I get when I run the above code.
buffered: 24 bytes
unsigned int: 1234
long long: 123123123
double: 343298374.123456776142
float: 234324.125000000000
Is there anything I miss or wrong?