簡體   English   中英

為什么我無法從std :: stringstream二進制流中獲得全精度(雙精度,浮點型)

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

我試圖從某些自定義結構(或類)創建二進制包。 我在c ++中使用std :: stringstream類創建了二進制包。 然后,我從流中還原它以驗證二進制包。 使用“ unsinged int”或“ long long”數據類型似乎很好。 但是,當涉及浮點數(“ float”或“ double”)時,我無法完全精確地恢復它。

這是我用於測試的簡單代碼。

#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() << " bytes\n"; // 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: %.*lf\n", 12, c_ddata);
  printf("float: %.*f\n", 12, c_fdata);  
}

我希望二進制流的大小為24個字節,並且我可以恢復所有數字而不會丟失任何信息。 但是,我無法完全精確地恢復double和float數。

這是運行上面的代碼時得到的輸出。

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

我有什么想念或做錯的嗎?

當您聲明它時,此時此刻您會失去精度:

  float fdata = 234324.1234567;

恢復后沒有。 另外,請記住您的解決方案不是可移植的:在具有不同字節序的體系結構之間無法正確還原數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM