c++arraysqthexqdebug

How can hex values of a QByteArray be shown without them being converted to ASCII characters


I have a short program that reads data from the serial port and stores it in a QByteArray. When I use qDebug() to show the contents of the array some of the hex values are shown as expected, eg. 0xB5 stays 0xB5, but others are changed to ASCII, eg. 0x62 becomes b.

Here is the code i use to read the data and to show it using qDebug:

void MainWindow::readSerial()
{
    QByteArray serialData = port->readAll();
    qDebug() << "SerialData: " <<serialData;
}

The program outputs the following:

SerialData: "\xB5""b\x0B\x01""0\x00:\x16Q\x1E

but I expect it to output something like this :

SerialData: \xB5\62\x0B......

My questions are:

  1. Does qDebug automatically convert some hex values to ASCII

  2. if so is there a way to stop it from doing so

  3. Does the QByteArray store the data accurately or may the problem lei in the way i am storing the data

Thanks for your help. Regards


Solution

  • Use QByteArray::toHex().

    void MainWindow::readSerial()
    {
        QByteArray serialData = port->readAll();
        qDebug() << "SerialData: " << serialData.toHex(':');
    }
    

    SerialData: B5:62:0B

    1) QDebug always shows the data as printable characters.

    2) You can manipulate the output somewhat using QTextStream operators. It will not help in this case though. Long and complicated answer is in the code (this is where QDebug eventually ends up for QByteArray printing).

    3) Yes it stores the data exactly as given.