Search code examples
c++qtfile-ioqbytearray

How to read 16 bit integer using QByteArray


I want to read a file with QByteArray but the problem is that it read byte wise and i want array of 16 bit integer. here is my code...

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

here is the test to find values inside

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

result:

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

these are because of 8 bit array i need 16 bit i,e.. at value at 0 = -344 (//binary// 1111 11110 1010 1000)


Solution

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