开发者

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 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.


You can also use qFromBigEndian

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


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'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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜