【轉】QT中QDataStream中浮點數輸出問題
阿新 • • 發佈:2019-01-02
先上程式碼:
C/C++ code ?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)