#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();
}
Run Code Online (Sandbox Code Playgroud)
以上不打印任何值。除了“tostr:”之外,它不会打印任何内容。如果我将 0x0A 存储在 uchar 中,然后将其推送到 qByteArray 中,那么这个问题就会消失。
我能以当前的形式打印它吗?
因为在许多编码中,您提供的字节是各种控制字符(换行符、回车符等)。通过std::string
并char*
意味着字节将按原样发送到终端,因此以这种方式显示(根本不显示,或显示为各种类型的空白)。
您可以尝试执行以下操作之一,具体取决于您的需求:
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.
Run Code Online (Sandbox Code Playgroud)
这些以各种转义序列打印字节(QString 使用 unicode,这就是为什么您在那里看到 \u 而不是 \x 的原因),作为可读的十六进制表示以及“原样”。
QDebug 对许多已知类型(如 QString 和 QByteArray)进行特殊格式化,这就是为什么上面的前三个示例用引号打印并写出转义序列(毕竟是为了调试)。qPrintable,它的工作方式与toStdString().c_str()
返回一个 char*非常相似,QDebug 不会以任何特殊方式对其进行格式化,这就是为什么您将空格作为输出(这与std::cout
和朋友的行为相同)。
归档时间: |
|
查看次数: |
11204 次 |
最近记录: |