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.
CodePudding user response:
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];
}
}