#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中,那么这个问题就会消失。
我可以做什么,打印它在其当前的形式?
发布于 2016-08-02 18:47:53
因为在许多编码中,您给出的字节是各种控制字符(换行符、回车符等)。通过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.它们打印各种escape sequences格式的字节(QString使用unicode,这就是为什么您在这里看到\u而不是\x ),作为可读的十六进制表示以及“原样”。
QDebug为许多已知的类型做了特殊的格式化,比如QString和QByteArray,这就是为什么上面的前三个例子用引号打印并写出转义序列(毕竟是为了调试)。qPrintable的工作方式与toStdString().c_str()非常相似,它返回一个字符*,QDebug不会以任何特殊的方式对其进行格式化,这就是为什么您会将空白作为输出(这是与std::cout和朋友相同的行为)。
https://stackoverflow.com/questions/38717467
复制相似问题