将 QByteArray 转换为 quint32 的向量

问题描述

我正在从二进制文件中读取 QByteArray,需要将其转换为 QVector<quint32>。我尝试了以下代码:

QVector<quint32> qByteArrayToQuint32Vector(const QByteArray bytes,QDataStream::ByteOrder byteOrder) {
   QByteArray temp;
   QVector<quint32> convertedData;
   QDataStream stream(&temp,QIODevice::ReadWrite);

   for (int i = 0; i < bytes.length(); i++) {
       stream << bytes[i];
   }

   stream.setByteOrder(byteOrder);
   quint32 t = 0;

   for (int i = 0; i < bytes.length(); i += 4) {
       stream >> t;
       convertedData.push_back(t);
   }

   return convertedData;
}

它不起作用,转换后的数据只是零。

解决方法

看来我误解了 QDataStream 的用法。工作解决方案如下:

QVector<quint32> qByteArrayToQuint32Vector(const QByteArray bytes,QDataStream::ByteOrder byteOrder) {

    int byteArraySize = bytes.length();
    int vectorLen = byteArraySize/4;

    QVector<quint32> convertedData;
    convertedData.resize(vectorLen);

    QDataStream in(bytes);
    in.setByteOrder(byteOrder);

    for (int i = 0; i < vectorLen; i++) {
        in >> convertedData[i];
    }

    return convertedData;
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...