为什么我无法从 std::stringstream 二进制流中获得全精度(双精度、浮点数)

Why I couldn't get full precision (double, float) from std::stringstream binary stream

本文关键字:精度 双精度 浮点数 std 为什么 二进制 stringstream      更新时间:2023-10-16

我正在尝试从某个自定义结构(或类(中创建一个二进制包。我在 c++ 中使用 std::stringstream 类创建了二进制包。然后,我从流中还原它以验证二进制包。对于"unsinged int"或"long long"数据类型似乎很好。但是,当涉及到浮点数("浮点数"或"双精度数"(时,我无法完全精确地恢复它。

这是我用于测试的简单代码。

#include <iostream>
#include <string>
void main() {
  unsigned int idata = 1234;
  long long lldata = 123123123;
  double ddata = 343298374.123456789012345;
  float fdata = 234324.1234567;
  std::stringstream ss(std::stringstream::in | std::stringstream::out | std::stringstream::binary);
  // write data
  ss.write(reinterpret_cast<const char*>(&idata), sizeof(unsigned int)); // 4 bytes
  ss.write(reinterpret_cast<const char*>(&lldata), sizeof(long long)); // 8 bytes
  ss.write(reinterpret_cast<const char*>(&ddata), sizeof(double)); // 8 bytes
  ss.write(reinterpret_cast<const char*>(&fdata), sizeof(float)); // 4 bytes
  // check buffer size
  ss.seekp(0, std::ios::end);
  std::cout << "buffered: " << ss.tellp() << " bytesn"; // expect 24 bytes
  // validate the stream
  unsigned int c_idata;
  long long c_lldata;
  double c_ddata;
  float c_fdata;
  ss.seekg(0);
  ss.read(reinterpret_cast<char*>(&c_idata), sizeof(unsigned int));
  ss.read(reinterpret_cast<char*>(&c_lldata), sizeof(long long));
  ss.read(reinterpret_cast<char*>(&c_ddata), sizeof(double));
  ss.read(reinterpret_cast<char*>(&c_fdata), sizeof(float));
  std::cout << "unsigned long: " << c_idata << std::endl;
  std::cout << "long long: " << c_lldata << std::endl;
  printf("double: %.*lfn", 12, c_ddata);
  printf("float: %.*fn", 12, c_fdata);  
}

我希望二进制流大小为 24 字节,我可以恢复所有数字而不会丢失任何信息。但是,我无法完全精确地恢复双精度和浮点数。

这是我运行上述代码时得到的输出。

buffered: 24 bytes
unsigned int: 1234
long long: 123123123
double: 343298374.123456776142
float: 234324.125000000000

有什么我错过或错的地方吗?

当你

声明它的这一刻,你会失去精度:

  float fdata = 234324.1234567;

恢复后不行。此外,请记住,您的解决方案不可移植:数据将无法在具有不同字节序的体系结构之间正确还原。