简体   繁体   English

读入四字节字符

[英]Reading in four byte char

What am i doing wrong reading the wav header? 我在读取wav标头时出了什么问题?

First 8 Bytes are: 52 49 46 46 94 e5 37 03 (1st 4 Bytes are meant to be chars, last 4 Bytes are int32 little endian) 前8个字节是:52 49 46 46 94 e5 37 03(第4个字节是字符,后4个字节是int32 little endian)

QFile wavFile(fileName);
QByteArray wavFileContent = wavFile.readAll();
qDebug() << "The size of the WAV file is: " << wavFileContent.size();

char *fileType = new char[4];
unsigned int fileSize;

QDataStream analyzeHeaderDS(&wavFileContent,QIODevice::ReadOnly);
analyzeHeaderDS.setByteOrder(QDataStream::LittleEndian);

analyzeHeaderDS.readRawData(fileType,4);    // "RIFF"
analyzeHeaderDS >> fileSize;                // File Size

qDebug() << "WAV File Header read:";
qDebug() << "File Type: "  << QString::fromUtf8(fileType);
qDebug() << "File Size: "  << fileSize;

The output is: 输出为:

The size of the WAV file is:  53994908 
WAV File Header read: 
File Type:  "RIFFH??i?5" 
File Size:  53994900 

Why is it not only "RIFF" but some other stuff? 为什么不仅是“ RIFF”,还有其他一些东西? I allocated a 4-byte char and read in 4 chars. 我分配了一个4字节的字符,并读取了4个字符。 The next value (file size) is correct. 下一个值(文件大小)正确。

QString::fromUtf8() expects a null terminated array of char . QString::fromUtf8()需要以char结尾的空终止数组。 You on the other hand have an array of char , with length 4, that is not null terminated. 另一方面,您有一个长度为4的char数组,该数组不以null结尾。 So your call to that method fails to meet requirements and the resulting behaviour is ill-defined. 因此,您对该方法的调用无法满足要求,并且导致的行为是不确定的。 You can consult the documentation to learn the details of this method: http://qt-project.org/doc/qt-5/qstring.html#fromUtf8 您可以查阅文档以了解此方法的详细信息: http : //qt-project.org/doc/qt-5/qstring.html#fromUtf8

If you pass the length of the array to fromUtf8() the function will not look for a null terminator: 如果将数组的长度传递给fromUtf8()该函数将不会查找空终止符:

QString::fromUtf8(fileType, 4);

I'm not sure that fromUtf8() is the right choice here. 我不确定fromUtf8()是这里的正确选择。 I rather suspect that fromLocal8Bit would be more appropriate. 我相当怀疑fromLocal8Bit会更合适。 So I'd have it like this: 所以我会这样:

QString::fromLocal8Bit(fileType, 4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM