1

I've written a small Packet class consisting of some quint8's, quint16's, QByteArrays and a quint32 that has a toByteArray() method to return a serialized version of the object, conforming to a protocol specification.

Packet Spec

  • Protocol identifier [4 byte] (Version 1 = 0x74697331)
  • Session ID, a MD5 hash salted with the timestamp + user IP. [16 bytes]
  • Command ID [1 byte]
  • Argument Size [2 byte]
  • Args [1-8,192 bytes]
  • CRC-B (X-25) [2 bytes]

Most of the data serializes fine. The exception is the last quint16 (my crc), which seems to get clobbered.

I don't believe the problem is in the declaration of my class. I've re-created the serialization function in this code sample which demonstrates the bug I'm receiving, without my packet class. (But the same final QByteArray layout)

(More) Minimal reproducible testcase

#include <iostream>

#include <QByteArray>
#include <QDebug>

using namespace std;

int main()
{
    QByteArray arr;

    quint32 m_protocolId = 0x74697331;
    QByteArray m_sessionId;
    m_sessionId.resize(16);
    m_sessionId.fill(0);
    quint8 m_commandId = 0x1;
    quint16 m_argsSize = 0x0e;
    QByteArray args;
    args.append("test").append('\0');
    args.append("1234qwer").append('\0');
    quint16 m_crc;
    m_crc = 0xB5A2;

    QDataStream out(&arr, QIODevice::WriteOnly);
    out.setByteOrder(QDataStream::LittleEndian);

    out << m_protocolId;
    out.writeRawData(m_sessionId.data(), 16);
    out << m_commandId;
    out << m_argsSize;
    out.writeRawData(args.data(), args.length());
    out << m_crc;

    foreach (char c, arr)
    {
        qDebug() << QString::number((int)c, 16).toAscii().data();
    }

    return 0;
}

Here's the output I get:

73 69 74 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 e 0 74 65 73 74 0 31 32 33 34 71 77 65 72 0 ffffffffffffffa2 ffffffffffffffb5

Those last two should be 0xa2, 0xb5. I guess it's some sort of alignment issue. Is there any way to correct this while still conforming to the packet spec?

4

1 に答える 1

1

デバッグ出力を微調整するだけでよいと思います。試す:

..
foreach (unsigned char c, arr)
..
于 2012-04-13T04:24:17.160 に答える