-1

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.

  • What are you expecting the result to be? for a short you can only have a max bit of 16. so you can represent the value as either 0 to 65535 or -32768 to 32767. 65535 which is in bytes is FFFF for unsigned. – agent_bean Mar 24 '22 at 11:14
  • Unsigned short will be fine. I just want each element to contain 2 bytes of data. – Soham Patel Mar 24 '22 at 11:33
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 24 '22 at 12:13

1 Answers1

2

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]);
    }
}

mugiseyebrows
  • 4,138
  • 1
  • 14
  • 15