QT中QDataStream中浮点数输出问题

转载:https://blog.csdn.net/weixin_33739646/article/details/86444997


先上代码:

C/C++ code
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 时,则可以正常输出,

C/C++ code
 
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();
}


此时输出结果正常

求高手解释原理!

算是自问自答吧,今天仔细看了一下帮助文档,原来在高版本中QDataStream中默认精度为double,所以需要在程序中将QDataStream中浮点数精度改为single,办法为QDataStream::setFloatingPointPrecision(QDataStream::singlePrecision)

发布了83 篇原创文章 · 获赞 24 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/LittleLittleFish_xyg/article/details/95455900