QString类型和unsigned char data怎样相互转换

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QString类型和unsigned char data怎样相互转换相关的知识,希望对你有一定的参考价值。

参考技术A QString转char:
QString ss = "..............";
char * cc = ss.toLatin1().data();

char转QString
QString string = QString(QLatin1String(cc)) ;
char * cc = ss.toLatin1().data(); // 可能会有问题

QByteArray bytes = ss.toLatin1();
const char* cc = bytes.data(); // 这样应该可以吧

QString unsigned char* 的转换

QString -> unsigned char* :
QString str = "ABCD";
 int length = str.length();
unsigned char* sequence = NULL;
sequence =(unsigned char*)qstrdup(str.toAscii().constData());
delete[] sequence;
- sequence length = 5 --> [‘A‘] [‘B‘] [‘C‘] [‘D‘] [‘/0‘]
- sequence is now "independant" from str
- sequence has to be deleted with -> delete [] sequence
QString -> char:
const QByteArray ba = string.toAscii(); // make ba const, because modifying this array might otherwise invalidate the pointer
const char* sequence = ba.constData(); // now sequence will remain valid within the current scope.

The call to toAscii() creates a temporary QByteArray which goes out of scope when used like this:
char *sequence = string.toAscii().constData();
// sequence is now a dangling pointer!

 

http://wxpjiujiang.blog.163.com/blog/static/203994030201292661134137/

以上是关于QString类型和unsigned char data怎样相互转换的主要内容,如果未能解决你的问题,请参考以下文章

字符串怎么转换为unsigned char数组

QString unsigned char* 的转换

qt上的char * 和 QString互相转换

数据类型为 unsigned char 时 scanf 的行为问题

数据库unsigned char*类型图片存进

zz Qt下 QString转char*和char []