如何从 unsigned char* 获取 Qstring?
How I can get the Qstring from unsigned char*?
我正在用 C++ 编写我的 Qt 程序。我正在从卡片 Reader 中读取一个值,但它的库为我提供了一个带有 unsigned char* 的值。我需要在 Qstring 中将其放入 QTextEdit 中。
我试过:
char* aux(reinterpret_cast<char*>(data->track2));
QString myString = QString::fromUtf8(aux);
我可以这样读取我的无符号字符:
for(int x = 0; x < len; x++){
printf("%02X", buf[x]);
}
但是我得到了非常奇怪的值。任何人都可以帮助我吗?或者如何将 unsigned char*
(buf) 推送到字符串中?
unsigned char* ch;
std::string test= (char*)ch;
QString sstr = QString::fromStdString(test);
我用过这个,效果很好。
UTF8 C 字符串
Qt 将其字符串存储为 UTF-16,之前(在 Qt3 中)为 UCS2。这意味着它与 C 字符串不同,因为该字符串基于 16 位(多字节)字符。
要将数据从 UTF8 编码的 C 字符串或数组和长度转换为 QString,您应该使用。
char data[] = "My string";
QString qstr1 = QString::fromUtf8(data);
QString qstr2 = QString::fromUtf8(data, strlen(data));
要转换回 C 字符串,您应该使用:
QByteArray bytes = qstr1.toUtf8();
const char* data = bytes.constData();
其他编码
如果您的数据不是 UTF-8,您将不得不使用不同的辅助函数。 Qt 提供 fromLatin1 and toLatin1 for simple European code pages, and also the local narrow code page with fromLocal8Bit and toLocal8Bit.
总结
您的 char*
与 Q 字符串的编码不同。不要尝试直接将单个字符(除非它们是单个代码点)添加到 Q 字符串。使用辅助函数确保您使用相同的编码组合数据。
我正在用 C++ 编写我的 Qt 程序。我正在从卡片 Reader 中读取一个值,但它的库为我提供了一个带有 unsigned char* 的值。我需要在 Qstring 中将其放入 QTextEdit 中。
我试过:
char* aux(reinterpret_cast<char*>(data->track2));
QString myString = QString::fromUtf8(aux);
我可以这样读取我的无符号字符:
for(int x = 0; x < len; x++){
printf("%02X", buf[x]);
}
但是我得到了非常奇怪的值。任何人都可以帮助我吗?或者如何将 unsigned char*
(buf) 推送到字符串中?
unsigned char* ch;
std::string test= (char*)ch;
QString sstr = QString::fromStdString(test);
我用过这个,效果很好。
UTF8 C 字符串
Qt 将其字符串存储为 UTF-16,之前(在 Qt3 中)为 UCS2。这意味着它与 C 字符串不同,因为该字符串基于 16 位(多字节)字符。
要将数据从 UTF8 编码的 C 字符串或数组和长度转换为 QString,您应该使用。
char data[] = "My string";
QString qstr1 = QString::fromUtf8(data);
QString qstr2 = QString::fromUtf8(data, strlen(data));
要转换回 C 字符串,您应该使用:
QByteArray bytes = qstr1.toUtf8();
const char* data = bytes.constData();
其他编码
如果您的数据不是 UTF-8,您将不得不使用不同的辅助函数。 Qt 提供 fromLatin1 and toLatin1 for simple European code pages, and also the local narrow code page with fromLocal8Bit and toLocal8Bit.
总结
您的 char*
与 Q 字符串的编码不同。不要尝试直接将单个字符(除非它们是单个代码点)添加到 Q 字符串。使用辅助函数确保您使用相同的编码组合数据。