3
#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();
}

以上不打印任何值。它不打印除“tostr:”之外的任何内容。如果我将 0x0A 存储在 uchar 中,然后将其推送到 qByteArray 中,那么这个问题就会消失。

我能以目前的形式打印它吗?

4

1 回答 1

8

因为在许多编码中,您给出的字节是各种控制字符(换行符、回车符等)。通过std::stringandchar*意味着字节将按原样发送到终端,并因此以这种方式显示(根本不显示,或显示为各种类型的空白)。

您可以尝试改用其中一种方法,具体取决于您想要什么:

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.

这些以各种转义序列打印字节(QString 使用 unicode,这就是为什么您在那里看到 \u 而不是 \x 的原因),作为可读的十六进制表示以及“原样”。

QDebug 对许多已知类型(如 QString 和 QByteArray)进行特殊格式化,这就是为什么上面的前三个示例使用引号打印并写出转义序列(毕竟它是用于调试的)。qPrintable,它的工作原理与返回一个 char* 非常相似toStdString().c_str(),QDebug 不会以任何特殊方式对其进行格式化,这就是为什么你得到空白作为输出的原因(这与std::cout和朋友的行为相同)。

于 2016-08-02T10:47:53.277 回答