c++ - 通过 qDebug 打印 qByteArray

标签 c++ qt qdebug

#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 中,那么这个问题就会消失。

如何以当前形式打印它?

最佳答案

因为你给的字节,在很多编码中,都是各种控制字符(换行,回车等)。通过 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 和 friend 的行为)。

关于c++ - 通过 qDebug 打印 qByteArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38717467/

相关文章:

qt - Qdebug 显示十六进制值

c++ - Char * 指针初始化

c++ - 对 double 的二维 vector 进行排序

c++ - 主窗口打开后显示一个按钮

c++ - Qt 无法与 g++ 链接

c++ - 在 QT 中重载 QDebug

eclipse - qDebug 和 cout 不起作用

c++ - 在 Windows 10 VS2015 上构建 Boost - 无法打开 *.lib

c++ - 在 Unix 上分离命令行输出(处理与用户交互)的方法是什么?

c++ - 在多个 Qmenu 中重用一个 QMenu