QByteArray to quint16
-
Hi,
I wrote code like below to change QByteArray to quint16 variable:
QByteArray data; data.resize(1); data[0] = 0x08; QDataStream stream(&data, QIODevice::ReadOnly); stream.setByteOrder(QDataStream::BigEndian); quint16 var; stream >> var; qDebug() << "Expected var = 8, but var = " << var;
But output is:
Expected var = 8, but var = 0
I know that quint16 is written on two bytes and QByteArray has one byte, but this is part of a larger code and I may happen that QByteArray will have two bytes as below:
QByteArray data; data.resize(2); data[0] = 0x08; data[1] = 0x04;
Then the output is correctly and var = 2052. How could I write a QByteArray with one byte to quint16?
-
@Creatorczyk Does this work:
quint8 var; stream >> var; quint16 var16 = var;
-
@Creatorczyk said in QByteArray to quint16:
but can I do this without creating quint8?
I guess you need two bytes in the QByteArray to make it work (fill it with a zero byte).
I don't know what QDataStream does if you ask it to give you a short but the underlying QByteArray contains only one byte (you can check the QDataStream source code if you want to know what happens). -
@Creatorczyk said in QByteArray to quint16:
How could I write a QByteArray with one byte to quint16?
quint16 var16 = qByteArray[0]
?As @jsulm has said, I don't think you're supposed to stream one byte into a two-byte variable. Sounds like it does something like only go into the first byte at the address, or maybe even does nothing at all, at least something dodgy.
-
@Creatorczyk said in QByteArray to quint16:
How could I write a QByteArray with one byte to quint16?
You cannot do that directly with a QDataStream. There are not enough bytes, so you will get a
QDataStream::ReadPastEnd
error: https://doc.qt.io/qt-5/qdatastream.html#Status-enum@jsulm suggested that you study the source code; the code for
QDataStream::operator>>()
is at https://code.woboq.org/qt5/qtbase/src/corelib/serialization/qdatastream.cpp.html#_ZN11QDataStreamrsERs -
@JKSH
Ah, I wondered whether it set an error and why the OP received0
as the result here. Answer from the code you referenced:if (readBlock(reinterpret_cast<char *>(&i), 2) != 2) { i = 0;
That's why the result is
0
, andreadBlock()
sets error flag from trying to read 2 bytes but only getting 1 viaconst int readResult = dev->read(data, len); if (readResult != len) setStatus(ReadPastEnd);
-
@JKSH said in QByteArray to quint16:
There are not enough bytes, so you will get a QDataStream::ReadPastEnd
For Qt 5.7 or later:
quint16 var; stream.startTransaction(); stream >> var; if(!stream.commitTransaction()){ quint8 tempVar; stream.startTransaction(); stream >> tempVar; if(!stream.commitTransaction()){ //handle this error } var=tempVar; }