C++ 将 QString 转换为无符号字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21857473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert QString into unsigned char array
提问by samoncode
I have a very basic question here. I tried googling for a while, because there are a lot of similar questions but none of the solutions worked for me.
我在这里有一个非常基本的问题。我尝试谷歌搜索了一段时间,因为有很多类似的问题,但没有一个解决方案对我有用。
here is a code snippet that shows the problem:
这是一个显示问题的代码片段:
QString test = "hello";
unsigned char* test1 = (unsigned char*) test.data();
unsigned char test2[10];
memcpy(test2,test1,test.size());
std::cout<<test2;
I try to fit the QString into the unsigned char array but the output I get is always just 'h'.
我尝试将 QString 放入无符号字符数组中,但我得到的输出始终只是“h”。
Can anyone tell me what is going wrong here?
谁能告诉我这里出了什么问题?
回答by 4pie0
Problem is in that QString.data()
returns a QChar*
but you want const char*
问题在于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
The assignment
那作业
unsigned char* test1 = (unsigned char*) test.data();
and trying to copy
并试图复制
unsigned char test2[10];
memcpy(test2,test1,test.size());
is wrong, because QChar
is 16 bit entityand as such trying to copy it will terminate because of 0 byte just after 'h'
.
是错误的,因为QChar
是 16 位实体,因此尝试复制它会因为'h'
.
回答by hank
In the second line you're trying to cast QChar*
to (unsigned char*)
which is completely wrong.
在第二行中,您试图将其强制QChar*
转换(unsigned char*)
为完全错误的。
Try this:
尝试这个:
QString test = "hello";
QByteArray ba = test.toLocal8Bit();
unsigned char *res = (unsigned char *)strdup(ba.constData());
std::cout << res << std::endl;