【问题标题】:Convert QString into unsigned char array将 QString 转换为无符号字符数组
【发布时间】:2014-03-18 10:12:00
【问题描述】:

我在这里有一个非常基本的问题。我尝试了一段时间的谷歌搜索,因为有很多类似的问题,但没有一个解决方案适合我。

这里有一段代码 sn-p 说明问题:

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

我尝试将 QString 放入 unsigned char 数组中,但是 我得到的输出总是'h'。

谁能告诉我这里出了什么问题?

【问题讨论】:

  • 请注意,QChar 是一个 16 位的东西,存储一个 Unicode 代码点。对于“h”(任何 US-ASCII),高位字节将为 0。这解释了为什么您的输出仅显示“h”。
  • @laune 谢谢。我不知道。

标签: c++ arrays qt qstring unsigned-char


【解决方案1】:

问题在于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 is 16 bit entity 并因此尝试复制它会因为'h' 之后的0 字节而终止。

【讨论】:

  • 谢谢!效果很好,正是我想做的!
【解决方案2】:

在第二行中,您尝试将 QChar* 转换为 (unsigned char*),这是完全错误的。

试试这个:

QString test = "hello";
QByteArray ba = test.toLocal8Bit();
unsigned char *res = (unsigned char *)strdup(ba.constData());
std::cout << res << std::endl;

【讨论】:

  • OP:除非你真的需要结果是可变的,否则不要strdup
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
  • 2017-09-17
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
  • 2010-10-23
  • 2013-07-11
相关资源
最近更新 更多