C++ - serialize double to binary file in little endian

Viewed 3398

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

3 Answers
Related