【问题标题】:How to read 16 bit integer using QByteArray如何使用 QByteArray 读取 16 位整数
【发布时间】:2014-11-06 06:45:21
【问题描述】:

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

【问题讨论】:

    标签: c++ qt file-io qbytearray


    【解决方案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);
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 感谢显示正确的结果,但我需要像 data16[i] 一样使用数组,因为 m 使用 qwtspectrogram 进行绘图。有没有办法以(data16 [i])格式排列数据...
      • 您可以将 data16 用作数组...数组的行为类似于指针。我已经更新了答案给你看
      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多