当前位置:   article > 正文

为什么QDataStream保存文件多出四个字节_quint32直接append到一个qbytearray对象中会固定占4个字节吗

quint32直接append到一个qbytearray对象中会固定占4个字节吗

我在使用QByteArray保存数据到QDataStream时,二进制文件中,发现头部多出4个字节,就像这样。

网上搜了一些文章,说这4个字节表示数据存储的长度,我比较关心怎样才可以去掉这4个字节,网上方法不详。

于是我调试了一下Qt源码,发现是这样的。

QDataStream的writeBytes接口实现中,会先写入数据长度len,所以调用writeBytes就会导致此现象。

  1. /*!
  2. Writes the length specifier \a len and the buffer \a s to the
  3. stream and returns a reference to the stream.
  4. The \a len is serialized as a quint32, followed by \a len bytes
  5. from \a s. Note that the data is \e not encoded.
  6. \sa writeRawData(), readBytes()
  7. */
  8. QDataStream &QDataStream::writeBytes(const char *s, uint len)
  9. {
  10. CHECK_STREAM_WRITE_PRECOND(*this)
  11. *this << (quint32)len;// write length specifier
  12. if (len)
  13. writeRawData(s, len);
  14. return *this;
  15. }

QByteArray在使用<<操作符输入到QDataStream时,会调用writeBytes,导致多出4个字节。

  1. QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
  2. {
  3. if (ba.isNull() && out.version() >= 6) {
  4. out << (quint32)0xffffffff;
  5. return out;
  6. }
  7. return out.writeBytes(ba.constData(), ba.size());
  8. }

然后我发现,使用writeRawData可以避免写入头4个字节的数据。

除了QByteArray,这些类使用<<对QDataStream输入时,也会多出4个字节。

QString

QBitArray

QPicture

const char*

如果只希望保存原始数据,就需要先从数据源中取出数据,再直接调用QDataStream的writeRawData接口即可。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/736736
推荐阅读
  

闽ICP备14008679号