一、QByteArray和QString之间的转换
- QByteArray转为QString
QByteArray byte;
QString string(byte);
- QString转为QByteArray
QString str;
QByteArray byte = str.toAscii();
QByteArray byte2 = str.toLatin1();
二、char数组与QByteArray之间的转换
- char数组转为QByteArray
char ch[]{'a','b','c'};
QByteArray byte(ch);
- QByteArray转为char数组
QByteArray byte;
char* str = byte.data();
三、char数组和QString之间的转换
- char数组转为QString
QString::fromLatin1()
可以将char数组转为QString,不过需要注意的是char数组没有以'\0'
结尾的时候需要传入char数组长度
char ch[]{'a', 'b','c'};
QString qstr = QString::fromLatin1(ch, 3));
char ch[]{'a', 'b','c','\0'};
QString qstr = QString::fromLatin1(ch));
QString qstr2(ch);
- QString转为char
QString str = "abcd";
char *chr = str.toLatin1().data();
char *chr2 = qPrintable(str);
四、将unsigned char数组转为QString表示的16进制
- unsigned char数组转为QString
unsigned char un_char[]{0xff, 0xee, 0xdd, 0xcc, 0xaa};
QString ucTos = QString(QByteArray((char*)un_char, 5).toHex());