为什么我无法从 std::stringstream 二进制流中获得全精度(双精度、浮点数)
Why I couldn't get full precision (double, float) from std::stringstream binary stream
我正在尝试从某个自定义结构(或类(中创建一个二进制包。我在 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;
恢复后不行。此外,请记住,您的解决方案不可移植:数据将无法在具有不同字节序的体系结构之间正确还原。
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何使双精度值的 C++ 和 C# 中的结果相同
- 使用浮点数和双精度数的非常小数字的数学
- 使用 Xcode 将双精度存储在数组C++中
- 在 C++ 中将双精度变量写入二进制文件
- 如何从字符串转换为双精度*
- 为什么我的数组双精度函数不起作用?
- 高精度双精度的 Sprintf 格式化问题
- C++ cout 将双精度对齐到精度 2 并正确对齐
- 无法获得固定的设置精度双精度以显示小数位
- 为什么我无法从 std::stringstream 二进制流中获得全精度(双精度、浮点数)
- 将精度双精度转换为字符串