我正在连接一个以十六进制格式发送数据的外部设备。它是形式
> %abcdefg,+xxx.x,T,+yy.yy,T,+zz.zz,T,A*hhCRLF
- CR LF 是回车换行符
- hh->校验和
- %abcdefg -> 标题
以上数据包中的每个字符都以十六进制表示形式发送(xx、yy、abcd 等被替换为实际数字)。问题是我最后将它存储在 const char* 中,在隐式转换期间,校验和表示 0x05 被转换为\0x05。这里\0 是空字符终止了我的字符串。当它不是时,这被认为是不正确的帧。虽然我可以将实现更改为处理原始字节(十六进制形式),但我只是想知道是否还有其他出路,因为它大大简化了字节处理。这就是程序员应该做的。
同样在 cutecom 中(在 LINUX RHEL 4 上)我检查了串行端口上的数据,我们还注意到 \0x05
而不是校验和的 5。
请注意,为了存储传入的数据,我正在使用
//store data from serial here
unsigned char Buffer[SIZE];
//convert to a QString, here is where problem arises
QString str((const char*)Buffer); of \0
QString 是 Qt 的“字符串”克隆。库在这里不是问题我也可以使用 STL,但 C++ 字符串库也在做同样的事情。以前有人尝试过这种类型的实验吗?请分享您的观点。
编辑
这是您也可以自己检查的示例代码:
#include <iostream>
#include <string>
#include <QString>
#include <QApplication>
#include <QByteArray>
using std::cout;
using std::string;
using std::endl;
int main(int argc,char* argv[])
{
QApplication app(argc,argv);
int x = 0x05;
const char mydata[] = {
0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99};
QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
printf("Hello %s\n",data.data());
string str("Hello ");
unsigned char ch[]={22,5,6,7,4};
QString s((const char*)ch);
qDebug("Hello %s",qPrintable(s));
cout << str << x ;
cout << "\nHello I am \0x05";
cout << "\nHello I am " << "0x05";
return app.exec();
}
最佳答案
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data(); // returns "Qt is great!"
关于c++ - 十六进制到字符串转换 C++/C/Qt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1258718/