簡體   English   中英

如何使用QByteArray讀取16位整數

[英]How to read 16 bit integer using QByteArray

我想用QByteArray讀取文件,但問題是它按字節讀取,我想要16位整數數組。 這是我的代碼...

 QByteArray fileBuf;
 sprintf_s(filepath, "c:/file.bin");}
 myfile.setFileName(filepath);
 if(!myfile.open(QIODevice::ReadOnly)) return;
 fileBuf=myfile.readAll();

這是在其中查找值的測試

 qint16 z;
 for(int test =0; test < 5 ; test++)
 {
  z= (fileBuf[i]);
 qDebug()<< i<<"is="<<z;

結果:

0 is= -88 (// in binary// 1111 1111 1010 1000)
1 is= -2   (// in binary// 1111 1111 1111 1110)
2 is= -64 
3 is= -3 
4 is= 52

這些是因為8位數組,我需要16位,即..在值為0 = -344(// binary // 1111 11110 1010 1000)

從QByteArray中獲取constData(或數據)指針,並強制轉換為qint16:

QByteArray fileBuf;
const char * data=fileBuf.constData();
const qint16 * data16=reinterpret_cast<const qint16 *>(data);
int len=fileBuf.size()/(sizeof(qint16));  //Get the new len, since size() returns the number of 
                                          //bytes, and not the number of 16bit words.

//Iterate over all the words:
for (int i=0;i<len;++i) {
    //qint16 z=*data16;  //Get the value
    //data16++;          //Update the pointer to point to the next value

    //EDIT: Both lines above can be replaced with:
    qint16 z=data16[i]        

    //Use z....
    qDebug()<< i<<" is= "<<z;
}
QFile myfile;
myfile.setFileName("c:/file.bin");
if(!myfile.open(QIODevice::ReadOnly)) return;

QDataStream data(&myfile);
data.setByteOrder(QDataStream::LittleEndian);
QVector<qint16> result;
while(!data.atEnd()) {
    qint16 x;
    data >> x;
    result.append(x);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM