QT中QDataStream中浮点数输出问题

rookieofrookie 2016-01-25 12:37:22
先上代码:

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile file1("test.dat");
if(!file1.open(QIODevice::WriteOnly))
std::cout<<"can not open file"<<std::endl;
QDataStream fout(&file1);
float f=80.4;
fout<<f;
std::cout<<"done!"<<std::endl;
file1.close();
return a.exec();
}

原意应该输出float类型的二进制文件,其长度应该为32bit即四字节,但输出结果如下图:

长度为8字节,后面四字节是多出来的
我将程序改成使用QByteArray 时,则可以正常输出,

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFile file1("test.dat");
if(!file1.open(QIODevice::WriteOnly))
std::cout<<"can not open file"<<std::endl;
QDataStream fout(&file1);
QByteArray byteArray;
QBuffer buffer1(&byteArray);
buffer1.open(QIODevice::WriteOnly);
QDataStream out(&buffer1);
float f=80.4;
out<<f;
fout.writeRawData(byteArray,sizeof(float));
std::cout<<"done!"<<std::endl;
file1.close();
return a.exec();
}

此时输出结果正常

求高手解释原理!
...全文
429 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
要name有个P用 2019-06-20
  • 打赏
  • 举报
回复
前几天 一个单经度 数据 我用4个字节 去接收。。这个数字 怎么都 变得 很异常。怎么都解决不了,后来 同事告诉我 QDataStream中默认精度为double 需要重新设置一下 单精度。。。我日
rookieofrookie 2016-01-26
  • 打赏
  • 举报
回复 1
算是自问自答吧,今天仔细看了一下帮助文档,原来在高版本中QDataStream中默认精度为double,所以需要在程序中将QDataStream中浮点数精度改为single,办法为QDataStream::setFloatingPointPrecision(QDataStream::singlePrecision)
赵4老师 2016-01-26
  • 打赏
  • 举报
回复

24,855

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧