且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++ - 以小端序列化双向二进制文件

更新时间:2022-10-25 09:29:36

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);
}

相关阅读

技术问答最新文章