tags:

views:

56

answers:

1
+2  Q: 

C macro to C++\Qt

I have the following c macro from the libpurple yahoo plugin:

#define yahoo_put16(buf, data) ( \
        (*(buf) = (unsigned char)((data)>>8)&0xff), \
        (*((buf)+1) = (unsigned char)(data)&0xff),  \
        2)

I want to implement the same as a function in my class witch would receive as a parameter a quint16 value and return it as a QByteArray I have the following but i don't seem to get the same result as with the macro above.

QByteArray YahooPacket::packQuint16(quint16 value) const
{
    QByteArray data;

    data.append(QByteArray::number((value >> 8) & 0xFF));
    data.append(QByteArray::number(value & 0xFF));

    return data;
}

How would i do to implement my function?

+2  A: 

QByteArray::number() creates the printable (string) version of the number which is probably not what you want. Use the QByteArray constructor that takes a buffer pointer and a size parameter. I think this will do what you want.

QByteArray YahooPacket::packQuint16(quint16 value) const
{
    QByteArray data;

    data.append(QByteArray(((char*)&value)+1,1));
    data.append(QByteArray((char*)&value,1));

    return data;
}
Arnold Spence
daniels
That's a good question. Hopefully I didn't misinterpret what they are doing.
Arnold Spence
No, you didn't misinterpret. Your version gives the same result as theirs and also yours looks more nice and clean. It seems that actually what they were doing was just setting the endianness. Too bad they didn't put that in a comment, i would've known from the start what to look for. I ended up using QDataStream and setByteOrder to write to the QByteArray.
daniels