Search code examples
c++qtqt5byteqbytearray

Qt: from a fixed number of bytes to an integer


Using Qt5.4, I build the function generateRandomIDOver2Bytes. It generates a random number and it puts it onto a variable that occupies exactly two bytes.

QByteArray generateRandomIDOver2Bytes() {
    QString randomValue = QString::number(qrand() % 65535);
    QByteArray x;
    x.setRawData(randomValue.toLocal8Bit().constData(), 2);
    return x;
}

My issue is reverting the so generated value in order to obtain, again, an integer. The following minimum example actually does not work:

QByteArray tmp = generateRandomIDOver2Bytes(); //for example, the value 27458 
int value = tmp.toUInt(); 
qDebug() << value; //it prints always 9

Any idea?


Solution

  • A 16 bit integer can be split into individual bytes by bit operations.

    This way, it can be stored into a QByteArray.

    From Qt doc. of QByteArray:

    QByteArray can be used to store both raw bytes (including '\0's) and traditional 8-bit '\0'-terminated strings.

    For recovering, bit operations can be used as well.

    The contents of the QByteArray does not necessarily result into printable characters but that may not (or should not) be required in this case.

    testQByteArrayWithUShort.cc:

    #include <QtCore>
    
    int main()
    {
      quint16 r = 65534;//qrand() % 65535;
      qDebug() << "r:" << r;
      // storing r in QByteArray (little endian)
      QByteArray qBytes(2, 0); // reserve space for two bytes explicitly
      qBytes[0] = (uchar)r;
      qBytes[1] = (uchar)(r >> 8);
      qDebug() << "qBytes:" << qBytes;
      // recovering r
      quint16 rr = qBytes[0] | qBytes[1] << 8;
      qDebug() << "rr:" << rr;
    }
    

    Output:

    r: 65534
    qBytes: "\xFE\xFF"
    rr: 65534