Nominate our 2022 Qt Champions!

[SOLVED] size inconsistent after converting QByteArray to QString

  • Hello, I have wrote the following code
    void PacketDisplayer::log(QString str)
    std::cout << str.toAscii().constData() << std::endl;

    void PacketDisplayer::packetReceiver(QByteArray packetBuffer)
    log(QString("buffer length:%1").arg(packetBuffer.length()));
    log(QString("string length:%1").arg(QString(packetBuffer).length()));

    The output of the code above is:

    buffer length:893
    string length:509

    I tried to converting the QByteArray to QString, but the result was cut. only the first 509 bytes were converted to QString.

    Maybe there is a '\0' character in the 510th character, but I have checked this by WireShark, there is not.

    Should I set some parameter or there is something I lost? Thank you in advance.

  • At line 9 you are directing Qt to convert a series of bytes into a Unicode string using QString::fromAscii(). Characters that fall outside the default 7-bit or 8-bit code page this function uses will be mangled. It's also possible, if the QTextCodec::setCodecForCStrings() is set to something like UTF-8, that the 893 bytes may only represent 509 characters, i.e. you have the entire string.

    Since we do not know what you are expecting the encoding to be or what the buffer actually contains we cannot tell you much more.

  • I know where is the problem now.

    The QByteArray just keep an array consist of bytes, it does not care the terminating character, but the QString cares.

    When I was trying to find the problem, I thought the length() implementation between QString and QByteArray is all the same, but they are not. When the length() returns different length, all we have to do is to check the string content. The memory editor would be a great tool to deal with this.

    It was just a stupid problem, I was using a fixed-length char array to store the packet, thus the remaining part of packet would be never store into the packetBuffer I created.

Log in to reply