本文介绍了C ++ - 以小尾数序列化双精度到二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现一个函数, double 以小端字节顺序写入二进制文件。

到目前为止,我有类 BinaryWriter 实现:

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

推荐答案

你没有写这个,但我假设你正在运行的机器是BIG endian,否则写一个double就像写一个int,只有它的8个字节。

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

这篇关于C ++ - 以小尾数序列化双精度到二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:04