如何解压缩QByteArray中打包的32位整数? [英] How to unpack 32bit integer packed in a QByteArray?

查看:324
本文介绍了如何解压缩QByteArray中打包的32位整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用串行通信,并且在QByteArray中接收32位整数,打包为4个单独的字节(little-endian). 我尝试使用QByteArray::toLong()从4个字节中解压缩该值,但转换失败并返回错误的数字:

I'm working with serial communication, and I receive 32bit integers in a QByteArray, packed in 4 separate bytes (little-endian). I attempt to unpack the value from the 4 bytes using QByteArray::toLong() but it fails the conversion and returns the wrong number:

quint8 packed_bytes[] { 0x12, 0x34, 0x56, 0x78 };
QByteArray packed_array { QByteArray(reinterpret_cast<char*>(packed_bytes),
                                     sizeof(packed_bytes)) };
bool isConversionOK;
qint64 unpacked_value { packed_array.toLong(&isConversionOK) };
// At this point:
// unpacked_value == 0
// isConversionOK == false

预期的unpacked_value为0x78563412(小尾数法解包).为什么转换失败?

The expected unpacked_value is 0x78563412 (little-endian unpacking). Why is the conversion failing?

推荐答案

您可以使用QDataStream读取二进制数据.

You can use a QDataStream to read binary data.

quint8 packed_bytes[] { 0x12, 0x34, 0x56, 0x78 };
QByteArray packed_array { QByteArray(reinterpret_cast<char*>(packed_bytes), sizeof(packed_bytes)) };
QDataStream stream(packed_array);
stream.setByteOrder(QDataStream::LittleEndian);
int result;
stream >> result;
qDebug() << QString::number(result,16);

这篇关于如何解压缩QByteArray中打包的32位整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆