如何使用QByteArray读取16位整数

时间:2014-09-12 06:45:52

标签: 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 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,e ..值为0 = -344(//二进制// 1111 11110 1010 1000)

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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