如何使用QByteArray读取16位整数

How to read 16 bit integer using QByteArray

本文关键字:16位 整数 读取 QByteArray 何使用      更新时间:2023-10-16

我想用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位i。。在0=-344(//二进制//1111 11110 1010 1000)处的值

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);
}

从QByteArray中获取constData(或data)指针,并强制转换为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;
}