tags:

views:

46

answers:

3

I have the following C macro from libpurple:

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

How can i write that as a function that will get as a parameter a QByteArray and retrun a quint16 value using the algorithm in the c macro above?

I've asked a similar question that will convert from quint16 to QByteArray here so basically what i am trying to do now is the reverse of that function.

Thanks.

+2  A: 

I would try something along the following lines (i.e. let QDataStream do the work for you, which can be constructed with a QByteArray, let's call it yourByteArray):

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

I hope that helps.

EDIT: This question looks somewhat related.

Greg S
Except this won't work. If you look at the link i posted you'll see that does quint16 to QByteArray you will see that the bits get shifted to something like QByteArray[0] will have the last 8bits of quint16 and QBytearray[1] will hafe the first 8bits of the quint16
daniels
@daniels: Take a look at http://doc.trolltech.com/4.7/qdatastream.html#setByteOrder, you can set the byte order/endianness of `QDataStream`.
Greg S
Yep, that was it, setByteOrder did the trick quite nice. I've also rewritten the function from the link i posted to use QDataStream. Thanks.
daniels
+2  A: 

Greg S's code works fine for me (Qt 4.6.2 and WinXP). quint16's least significant bits come from QByteArray[1] and the most significant bits come from QByteArray[0]. But if you want exact control how the quint16 is constructed, get both bytes for the byte array and construct quint16 from those:

QDataStream dataStream(yourByteArray);
quint8 byte0;
quint8 byte1;
dataStream >> byte0 >> byte1;
quint16 result = (byte0 << 8) + byte1;
Roku
I've accepted Greg S's answer as using QDataStream seems more elegant. It didn't work at first for me because i wasn't setting the byte order/endianness for the data stream. Thank you for your answer witch is also correct but i can accept only one answer unfortunately. Upvoted.
daniels
+1  A: 

You can also use qFromBigEndian

QByteArray bytes;
...
quint16 result = qFromBigEndian<quint16>((uchar*)bytes.data());
Stephen Chu