我有一个像这样的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 ushortIdx0;
if ( idx0.size() >= sizeof(ushortIdx0) ) {
ushortIdx0 = *reinterpret_cast<const unsigned short *>( idx0.data() );
}
调试器将 ushortIdx0
值显示为 0
:
// Debugger shows:
//
// ushortIdx0 0 unsigned short
但是,当我通过 this website 将 0x 00 00 01 00
的 Little Endian 值转换为 UINT32 - Little Endian
时,我得到:
UINT32 - Little Endian (DCBA): Raw UINT32 00 01 00 00 65536
为什么 that website 的结果与我通过代码得到的不同吗?我不明白。我感谢任何帮助。
最佳答案
根据评论,您不能总是假设 unsigned short
具有一定的大小。如果您知道需要一个具有一定位数的无符号整数,则使用 cstdint
中的适当类型。 -- 在本例中为 uint32_t
。
关于字节序问题,既然您使用的是Qt
,为什么不使用 QDataStream
以与平台无关的方式序列化/反序列化数据。使用...写入无符号 32 位整数
quint32 data = ...;
QByteArray ba;
QDataStream ds(&ba, QIODevice::ReadWrite);
ds << data;
类似地读回数据。
关于c++ - 将 QByteArray 转换为无符号短整型 : not as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52126402/