【问题标题】:Convert QByteArray to unsigned short: not as expected将 QByteArray 转换为 unsigned short:不符合预期
【发布时间】:2019-02-07 03:10:58
【问题描述】:

我有一个这样的QByteArray

QByteArray idx0;

// idx0 is then assigned 4 bytes,
// idx0 content is shown on debugger as:

// idx0 "\000\000\001\000"  QByteArray
//          '\0'    0       0x00    char
//          '\0'    0       0x00    char
//                  1       0x01    char
//          '\0'    0       0x00    char

我将QbyteArray 转换为unsigned short,如下所示:

unsigned short ushortIdx0;
if ( idx0.size() >= sizeof(ushortIdx0) ) {
    ushortIdx0 = *reinterpret_cast<const unsigned short *>( idx0.data() );
}

调试器将ushortIdx0 值显示为0

// Debugger shows:
//
// ushortIdx0   0   unsigned short

但是,当我将 0x 00 00 01 00 的 Little Endian 值通过 this website 转换为 UINT32 - Little Endian 时,我得到:

UINT32 - 小端(DCBA): 原始 UINT32 00 01 00 00 65536

为什么that website 的结果与我通过代码得到的不同?我不明白。感谢您的帮助。

【问题讨论】:

  • 是什么让你确定sizeof(unsigned short) 是4?
  • @G.M.让我检查一下...
  • @user3405291 *reinterpret_cast&lt;const unsigned short *&gt;( idx0.data() ) 是未定义的行为。
  • @G.M.哇!我仔细检查了:sizeof(unsigned short): 2,因此我的假设完全错误。
  • 除此之外,您永远不应该假设您的机器具有一定的字节顺序!使用qFromLittleEndian 在任何机器上获得一致的结果。

标签: c++ qt qbytearray


【解决方案1】:

根据评论,您不能总是假设 unsigned short 是特定大小。如果你知道你需要一个具有一定位数的无符号整数,那么在这种情况下使用来自cstdint 的适当类型——uint32_t

关于字节序问题,既然您使用的是Qt,为什么不使用QDataStream 以与平台无关的方式序列化/反序列化数据。使用...写入一个无符号的 32 位整数。

quint32 data = ...;
QByteArray ba;
QDataStream ds(&ba, QIODevice::ReadWrite);
ds << data;

类似地读取数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2014-02-19
    • 2011-05-19
    • 2015-08-20
    • 2015-01-20
    相关资源
    最近更新 更多