Important: Please read the Qt Code of Conduct -

QByteArray to QString just like QDebug style

  • I have a QByetArray like this in QDebug():
    "\x01\x02""en\x80\xB1\x04\x0B\x01\x06vovo_euteamo\x00\f2J\f3e\f2l\f1l\f2y \f2C\f3l\f1u\f2b \fJ|\f2S\f1E\fJ| \fEMe\fM0\fEw ..."
    but I need it exactly the same way it is in QDebug(). For instance I need "\x00\f..." to find out that data type has changed. I can't simply iterate in QByteArray. However, things like "toStdString()" doesn't sustain it's qDebug() appearance. I want the description in qDebug() docs:
    "Normally, QDebug prints the array inside quotes and transforms control or non-US-ASCII characters to their C escape sequences (\xAB). This way, the output is always 7-bit clean and the string can be copied from the output and pasted back into C++ sources, if necessary."
    I know I can work with:

    QString::fromStdString( qByteArray.toStdString());

    but I'm working with a python script which works with "7-bit clean" just like what qDebug() outputs.
    Is there any way to have a QString with exactly same appearance of qDebug() output from a QByteArray?

  • Moderators

    hi, I usually go woth something like this, for a user readable display of hex data, this is however in C++ as I'm notusing Phyton :-(

    QString s; QByteArray data;
    for(int i = 0; i < data.size(); i++)
            s.append("0x"+QString::number(static_cast<unsigned char>(data[i]),16).toUpper().rightJustified(2,'0')+ " ");
    hope it helps.

  • @J.Hilk
    Thanks for you response but the problem is that in qDebug() I have "\f2J". This is only a "J" character. When converting back into number such as hex the "f2" is lost. It only writes "J" as number. While "f2" saves much work of me for another code. In python data seems to be normally read as qDebug() style in Qt. But output of "QString::fromStdString( qByteArray.toStdString());" will be:
    "\x01\x02""en\x80\xB1\x04\x00\x00\n\x00\f2J\f3e\f2l..." is converted into ->
    Here I have those "f"s but something like "\x80\xB1" is converted into "??"! While qDebug() can normally convert into cross language system but I have no idea how to get it. Maybe strange tricks like copy contents of console as they are written!
    What you mentioned is like "toHex" with some spaces among them. With the Hex I can't find out whether it was \x## or \f#(Char), I just have some numbers.

  • Moderators

    escape the backslash (\\)

  • @SomeoneElse
    Sorry, it works. I didn't see that it outputs all characters. That's a good idea. But I wait some days to see if somebody may have an idea to get qDebug() output. Now I can regenerate that string for python.
    Many thanks @J-Hilk

  • @raven-worx
    Ah sorry maybe I didn't catch that. Those quoted stuff with backslashes are console output, they are not inside code.

Log in to reply