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
But don't forget generally int is 4 octects and double is 8 octets.
Other problem is static_cast. See this example :
double d = 6.1; char c = static_cast(d); //c == 6
Solution reinterpret value with pointer :
After, you can use write( Int_64 *v ), which is a extension from write( Int_t v ).
You can use this method with :
Don't forget size_of(double) depend of system.
A little program converting doubles to an IEEE little endian representation. Besides the test in to_little_endian, it should work on any machine.
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.