Printing qByteArray through qDebug

Aquarius_Girl picture Aquarius_Girl · Aug 2, 2016 · Viewed 11.5k times · Source
#include <QCoreApplication>
#include <QByteArray>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QByteArray dataReceivedFromSerialPort;

    dataReceivedFromSerialPort.push_back(0x0A);
    dataReceivedFromSerialPort.push_back(0x0B);
    dataReceivedFromSerialPort.push_back(0x0C);
    dataReceivedFromSerialPort.push_back(0x0D);
    dataReceivedFromSerialPort.push_back(0x0E);
    dataReceivedFromSerialPort.push_back(0x0F);
    dataReceivedFromSerialPort.push_back(0x07);
    dataReceivedFromSerialPort.push_back(0x02);
    dataReceivedFromSerialPort.push_back(0x01);
    dataReceivedFromSerialPort.push_back(0x02);

    qDebug() << "tostr: " << dataReceivedFromSerialPort.toStdString().c_str();


    return a.exec();
}

The above does not print any value. It doesn't print anything beyond "tostr: ". If I store 0x0A in uchar and then push it in qByteArray then this problem disappears.

What can I do print it in its current form?

Answer

Jan picture Jan · Aug 2, 2016

Because the bytes you give are, in many encodings, various control characters (newlines, carriage returns, etc.). Going through std::string and char* means the bytes will be sent as they are to the terminal, and thus displayed that way (either not at all, or as various types of whitespace).

You can try to instead do one of these, depending on what you want:

qDebug() << dataFromSerialPort; // prints "\n\x0B\f\r\x0E\x0F\x07\x02\x01\x02"
qDebug() << QString::fromLatin1(dataFromSerialPort); // prints "\n\u000B\f\r\u000E\u000F\u0007\u0002\u0001\u0002"
qDebug() << dataFromSerialPort.toHex(); // "0a0b0c0d0e0f07020102"
qDebug() << qPrintable(dataFromSerialPort); // same as toStdString().c_str(), but IMO more readable.

These print the bytes in various escape sequences (QString uses unicode, that's why you see \u instead of \x there), as a readable hexadecimal representation as well "as is".

QDebug does special formatting for many known types, like QString and QByteArray, that is why the first three examples above print with quotes and write out the escape sequences (it's for debugging after all). qPrintable, which works very similar to toStdString().c_str() returns a char*, which QDebug does not format in any special way, which is why you get whitespace as the output (this is the same behaviour as std::cout and friends).