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
The expected unpacked_value
is 0x78563412 (little-endian unpacking). Why is the conversion failing?
you can build your qint64 with bit manipulators:
You can use a
QDataStream
to read binary data.toLong()
converts a char * digitsstring
to long. Not bytes. And your values likely don't make the up the string "0x78563412" or its decimal equivalent. Hence the 0 result.If you need the byte values interpreted as long you can do something like:
Or to access an array of bytes as long array:
Don't know whether my examples work out of the box but it should make clear the principle.
Check out this example:
the output is:
You may need to change the byte order depending on the endianess. But it does what you need.