c++qtshortqbytearray

QByteArray to short Int array in QT C++


I am receiving a QByteArray from UDP Socket. The QByteArray is of 52 elements each containing values from 0 to 9 - A to F. Now, I want to convert this QByteArray into a short int array of 13 elements such that first 4 elements of the QByteArray are stored in first element of short int array.

Eg. QByteArray = (002400AB12CD) -> ShortINT = [0024,00AB,12CD]

I have tried concatenating 4 elements and then convert them to Short INT.


Solution

  • You can use QByteArray::data() and QByteArray::constData() to access pointer to stored data and use c cast or reinterp_cast to cast specific type. Also you need to know endianness of data is it big-endian or little endian.

    #include <QByteArray>
    #include <QDebug>
    #include <QtEndian>
    
    void test() {
        QByteArray data("\x00\x24\x00\xAB\x12\xCD", 6);
        qint16_be* p = (qint16_be*) data.data();
        int l = data.size() / sizeof(qint16_be);
        for (int i=0; i<l; i++) {
            qDebug() << i << hex << p[i];
        }
    }
    

    Qt 4 does not have _be types. You can use qFromBigEndian or qbswap to swap bytes.

    #include <QByteArray>
    #include <QDebug>
    #include <QtEndian>
    
    void test() {
        QByteArray data("\x00\x24\x00\xAB\x12\xCD", 6);
        qint16* p = (qint16*) data.data();
        int l = data.size() / sizeof(qint16);
        for (int i=0; i<l; i++) {
            qDebug() << i << hex << qFromBigEndian(p[i]);
        }
    }