将QString转换为无符号字符数组

4

我有一个非常基础的问题。我尝试过谷歌搜索一段时间,因为有很多类似的问题,但没有一个解决方案适用于我。

这是一个代码片段,展示了问题:

QString test = "hello";
unsigned char* test1 = (unsigned char*) test.data();
unsigned char test2[10];
memcpy(test2,test1,test.size());
std::cout<<test2;

我尝试将QString适配到无符号字符数组中,但是输出结果始终只有“h”。

有人能告诉我这里出了什么问题吗?


2
请注意,QChar是一个16位的东西,存储Unicode代码点。对于一个 'h'(任何US-ASCII字符),高位字节将为0。这就解释了为什么你的输出只显示 'h'。 - laune
@laune 谢谢。我不知道那个。 - samoncode
3个回答

8
问题在于QString.data()返回的是QChar*,但你需要的是const char*
QString test = "hello";
unsigned char test2[10];
memcpy( test2, test.toStdString().c_str() ,test.size());
test2[5] = 0;
qDebug() << (char*)test2;
             ^^^
            this is necessary becuase otherwise
            just address is printed, i.e. @0x7fff8d2d0b20

这项任务

unsigned char* test1 = (unsigned char*) test.data();

并尝试复制

unsigned char test2[10];
memcpy(test2,test1,test.size());

这是错误的,因为QChar是16位实体,因此尝试复制它将在'h'之后的0字节处终止。


谢谢!它完美地工作了,正是我想要的! - samoncode

3
在第二行中,你试图将 QChar* 强制转换为 (unsigned char*),这是完全错误的。
尝试这样做:
QString test = "hello";
QByteArray ba = test.toLocal8Bit();
unsigned char *res = (unsigned char *)strdup(ba.constData());
std::cout << res << std::endl;

除非你真的需要结果是可变的,否则不要使用 strdup - Sebastian Redl

0

如果您想在QString中使用用俄语编写的sim卡,请使用此方法。

unsigned char* temp;
QString name = "М102";
QByteArray ba = name.toUtf8();
temp = (unsigned char*)ba.data();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接