Convert QByteArray to quint16

I have the following C macro from libpurple:

#define yahoo_get16(buf) ((((*(buf))<<8)&0xff00) + ((*((buf)+1)) & 0xff))

How can I write this as a function that takes a QByteArray as a parameter and returns a quint16 value using the algorithm in the c macro above?

I asked a similar question that will convert from quint16 to QByteArray here , so basically what I'm trying to do now is the flip side of this function.

Thank.

+3
source share
3 answers

I would try something along the following lines (i.e., let it QDataStreamdo the work for you, which can be built using QByteArray, call yourByteArray on it):

QDataStream dataStream(yourByteArray);
quint16 foo;
dataStream >> foo;

I hope this helps.

EDIT: question .

+2

qFromBigEndian

QByteArray bytes;
...
quint16 result = qFromBigEndian<quint16>((uchar*)bytes.data());
+4

Greg S code works fine for me (Qt 4.6.2 and WinXP). The least significant bits of quint16 come from QByteArray [1], and the most significant bits come from QByteArray [0]. But if you want to control exactly how quint16 is built, get both bytes for the byte array and build quint16 from them:

QDataStream dataStream(yourByteArray);
quint8 byte0;
quint8 byte1;
dataStream >> byte0 >> byte1;
quint16 result = (byte0 << 8) + byte1;
+2
source

Source: https://habr.com/ru/post/1768992/


All Articles