Qt QString hex value to QByteArray

mcan picture mcan · Oct 9, 2013 · Viewed 9.4k times · Source

I have a function which gives data as string and function put it to QByteArray and Socket transfer this array to host. When i try

_strdata = "80200000"

this data is hex data. transferred data should be 0x80200000 on wireshark.

my tries:

void DataTransmitter(const QString & _strdata)
{
   QByteArray myData = QByteArray::fromHex(_strdata.toLatin1());

   PUDPSocket->writeDatagram(myData.data(), myData.size(), host, port);
}

OUTPUT: wireshark: malformed packet

void DataTransmitter(const QString & _strdata)
{
    QString d1,d2,d3,d4;
    d1.append(_strdata[0]);d1.append(_strdata[1]);
    d2.append(_strdata[2]);d2.append(_strdata[3]);
    d3.append(_strdata[4]);d3.append(_strdata[5]);
    d4.append(_strdata[6]);d4.append(_strdata[7]);

    QByteArray data;
    data.append((char) d1.toInt());
    data.append((char) d2.toInt());
    data.append((char) d3.toInt());
    data.append((char) d4.toInt());

    PUDPSocket->writeDatagram(data.data(),data.size(),host,port);
    d1.clear();
    d2.clear();
    d3.clear();
    d4.clear();
}

OUTPUT: wireshark: malformed packet again

when i change data to "80200001" wireshark: 50:14:00:01

I need your suggestions,

Thank you, Can

Answer

drescherjm picture drescherjm · Oct 9, 2013

Your toInt() calls are using a base 10 conversion of your text.

You need to use base 16 for the toInt() calls like this:

 bool bOk;
 d1.toInt(&bOk,16);

So the whole code would be:

 void DataTransmitter(const QString & _strdata)
{
    QString d1,d2,d3,d4;
    d1.append(_strdata[0]);d1.append(_strdata[1]);
    d2.append(_strdata[2]);d2.append(_strdata[3]);
    d3.append(_strdata[4]);d3.append(_strdata[5]);
    d4.append(_strdata[6]);d4.append(_strdata[7]);

    bool bOK;
    QByteArray data;
    data.append((char) d1.toInt(&bOK,16));
    data.append((char) d2.toInt(&bOK,16));
    data.append((char) d3.toInt(&bOK,16));
    data.append((char) d4.toInt(&bOK,16));

    PUDPSocket->writeDatagram(data.data(),data.size(),host,port);
    d1.clear();
    d2.clear();
    d3.clear();
    d4.clear();
}

Edit: As you point out below fixing this does not solve the malformed packet problem. And your other example that uses Qt to convert from a string containing hex did not work either. I believe the problem is not due to the conversion but is a problem with the packet you are creating. I am not familiar with socket programming to help with this.