C++ 如何使用QByteArray读取16位整数

C++ 如何使用QByteArray读取16位整数,c++,qt,file-io,qbytearray,C++,Qt,File Io,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 t

我想用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;
这是因为8位数组我需要16位i,即。。值为0=-344(//binary//11111110 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;
}
QByteArray文件buf;
const char*data=fileBuf.constData();
const qint16*data16=重新解释(数据);
int len=fileBuf.size()/(sizeof(qint16))//获取新的len,因为size()返回
//字节,而不是16位字的数量。
//重复所有单词:
对于(inti=0;i
QFile-myfile;
myfile.setFileName(“c:/file.bin”);
如果(!myfile.open(QIODevice::ReadOnly))返回;
QDataStream数据(&myfile);
setByteOrder(QDataStream::LittleEndian);
矢量结果;
而(!data.atEnd()){
qint16-x;
数据>>x;
结果:追加(x);
}

谢谢,这显示了正确的结果,但我需要数组来像data16[I]一样使用,因为我使用qwtspectrogram来绘图。有没有办法将数据以(data16[I])格式排列……您可以将data16用作数组……数组的行为就像指针。我已经更新了答案,向您展示
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);
}