【问题标题】:Printing qByteArray through qDebug通过 qDebug 打印 qByteArray
【发布时间】:2016-12-07 15:11:30
【问题描述】:
#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 中,那么这个问题就消失了。

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

【问题讨论】:

  • 为什么你要经历这些转化,而不是仅仅使用qDebug() &lt;&lt; dataReceived;
  • 该示例按设计工作。我不太明白你想做什么。如果你想引用不可打印的代码,你必须明确地这样做。 dataReceivedFromSerialPort 应该是您的本地编码,即 UTF-8。如果不是,则由您自己按摩以进行展示。

标签: c++ qt qdebug


【解决方案1】:

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

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

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.

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

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

【讨论】:

  • 这个想法(对于 QByteArray 和 QString)是引用输出,以便您可以将其 C&P 到 C++ 源代码中。
猜你喜欢
  • 2012-06-10
  • 2016-03-25
  • 2017-06-05
  • 1970-01-01
  • 2021-10-11
  • 2012-04-12
  • 2015-04-23
  • 1970-01-01
  • 2011-06-14
相关资源
最近更新 更多