QDataStream有时使用32位浮点数,有时使用40位浮点数 [英] QDataStream uses sometimes 32 bit and sometimes 40 bit floats
问题描述
我正在编写一个应将浮点数组写入WAVE文件的应用程序.我为此使用了QDataStream,但这导致了我无法解释的非常不可能的输出.似乎QDataStream有时选择32位浮点数,有时选择40位浮点数.由于必须遵守严格的格式,因此会弄乱整个输出文件.
I am writing an application that is supposed to write an array of floats to a WAVE file. I am using a QDataStream for this, but this results in a very improbable output that I can't explain. It seems like the QDataStream sometimes chooses 32 bit floats and sometimes 40 bit floats. This messes up the entire output file, since it has to obey a strict format.
我的代码大致如下:
float* array;
unsigned int nSamples;
void saveWAV(const QString& fileName) const
{
QFile outFile(fileName);
if (outFile.open(QIODevice::WriteOnly | QIODevice::Text))
{
QDataStream dataStream(&outFile);
dataStream.setByteOrder(QDataStream::LittleEndian);
dataStream.setFloatingPointPrecision(QDataStream::SinglePrecision);
// ... do all the WAV file header stuff ...
for(int ii = 0; ii < nSamples; ++ii)
dataStream << array[ii];
}
}
我认为没有任何理由使这段代码有如此副作用.因此,我举了一个最小的例子来了解正在发生的事情.我将for循环替换为此:
I can think of no reason of how this code could have such a side-effect. So I made a minimal example to find out what was going on. I replaced the for-loop by this:
float temp1 = 1.63006e-33f;
float temp2 = 1.55949e-32f;
dataStream << temp1;
dataStream << temp1;
dataStream << temp2;
dataStream << temp1;
dataStream << temp2;
然后我使用Matlab打开输出文件,并查看写入文件的字节.这些是:
Then I opened the output file using Matlab and had a look at the bytes written the file. Those were:
8b 6b 07 09 // this is indeed 1.63006e-33f (notice it's Little Endian)
8b 6b 07 09
5b f2 a1 0d 0a // I don't know what this is but it's a byte to long
8b 6b 07 09
5b f2 a1 0d 0a
我随意选择了这些值,它们恰好具有这种作用.一些值导出为4字节,另一些导出为5字节数字.有谁知道这可能是什么原因?
I chose the values pretty arbitrarily, they just happened to have this effect. Some values are exported as 4-byte and other ones as 5-byte numbers. Does anyone have any idea what may be the cause of this?
修改:
检查两个浮子的大小时,它们似乎确实是4 char
长,但是:
When checking the size of both floats, they do seem to be 4 char
s long, though:
qDebug() << sizeof(temp1); // prints '4'
qDebug() << sizeof(temp2); // prints '4'
推荐答案
答案就在于输出文件的打开:QIODevice::Text
标志应该被省略了,因为它是一个二进制文件.如果包含文本标志,则在每个0a
之前插入一个0d
字符.因此,每个包含0a
字符的浮点数似乎都会因此而char
更长.
The answer lies in the opening of the output file: the QIODevice::Text
flag should have been left out, since it is a binary file. If the text-flag is included, a 0d
character is inserted before each 0a
. So each float that contains an 0a
character seems a char
longer because of this.
此答案的所有学分归于以下给出的答案: 浮动长度在32到40位之间变化
All credits for this answer go to the answers given in: Length of float changes between 32 and 40 bit
这篇关于QDataStream有时使用32位浮点数,有时使用40位浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!