先上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 时,则可以正常输出,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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)