C++ - serialize double to binary file in little endian
binaryfiles, c++, double, serialization
Solution
You didn't write this, but I'm assuming the machine you're running on is BIG endian, otherwise writing a double is the same as writing an int, only it's 8 bytes.
const int __one__ = 1;
const bool isCpuLittleEndian = 1 == *(char*)(&__one__); // CPU endianness
const bool isFileLittleEndian = false; // output endianness - you choose :)
void BinaryWriter::write( double v )
{
if (isCpuLittleEndian ^ isFileLittleEndian) {
char data[8], *pDouble = (char*)(double*)(&v);
for (int i = 0; i < 8; ++i) {
data[i] = pDouble[7-i];
}
m_fstream.write(data, 8);
}
else
m_fstream.write((char*)(&v), 8);
}
Problem
I'm trying to implement a function that writes `double` to binary file in little endian byte order. So far I have class `BinaryWriter` implementation: ``` void BinaryWriter::open_file_stream( const String& path ) { // open output stream m_fstream.open( path.c_str(), std::ios_base::out | std::ios_base::binary); m_fstream.imbue(std::locale::classic()); } void BinaryWriter::write( int v ) { char data[4]; data[0] = static_cast<char>(v & 0xFF); data[1] = static_cast<char>((v >> 8) & 0xFF); data[2] = static_cast<char>((v >> 16) & 0xFF); data[3] = static_cast<char>((v >> 24) & 0xFF); m_fstream.write(data, 4); } void BinaryWriter::write( double v ) { // TBD } ``` `void BinaryWriter::write( int v )` was implemented using Sven answer to What is the correct way to output hex data to a file? post. Not sure how to implement `void BinaryWriter::write( double v )`. I tried naively follow `void BinaryWriter::write( int v )` implementation but it didn't work. I guess I don't fully understand the implementation. Thank you guys