0

我想用 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)

4

2 回答 2

1
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);
}
于 2014-09-12T08:37:02.527 回答
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;
}
于 2014-09-12T06:54:46.450 回答