我正在尝试实现一个以小尾数字节顺序将double
写入二进制文件的功能。
到目前为止,我有BinaryWriter
类的实现:
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 )
是使用Sven answer到What is the correct way to output hex data to a file?发布实现的。不确定如何实现
void BinaryWriter::write( double v )
。我尝试过天真地遵循
void BinaryWriter::write( int v )
的实现,但是没有用。我想我不完全了解实现。谢谢
最佳答案
您没有写这个,但是我假设您正在运行的机器是BIG endian,否则写一个double与写一个int相同,只有8个字节。
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);
}