简体   繁体   中英

Reading in four byte char

What am i doing wrong reading the wav header?

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)

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? I allocated a 4-byte char and read in 4 chars. The next value (file size) is correct.

QString::fromUtf8() expects a null terminated array of char . You on the other hand have an array of char , with length 4, that is not null terminated. 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

If you pass the length of the array to fromUtf8() the function will not look for a null terminator:

QString::fromUtf8(fileType, 4);

I'm not sure that fromUtf8() is the right choice here. I rather suspect that fromLocal8Bit would be more appropriate. So I'd have it like this:

QString::fromLocal8Bit(fileType, 4);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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