QString转QByteArray
toLatin1(),toLocal8Bit(),toUtf8() 都返回QByteArray类型(也就是说QString调这几个方法就能转成QByteArray)
区别在于返回的字符串编码方式不同
toLocal8Bit:本地操作系统设置的字符集编码
toLatin1:ASCII编码
toUtf8:UTF-8编码
QString str("hello");
QByteArray bytes = str.toUtf8(); // QString转QByteArray方法1
QString str("hello");
QByteArray bytes = str.toLatin1(); // QString转QByteArray方法2
QByteArray 不以\0结尾,String在c++11之后以\0结尾,c字符串以\0结尾
QByteArray转QString
QByteArray bytes("hello world");
QString string = bytes; // QByteArray转QString方法1
QByteArray bytes("hello world");
QString string;
string.prepend(bytes);// QByteArray转QString方法2
qDebug() << string;
QString转换为char*
QString str;
char* ch;
QByteArray ba = str.toLatin1(); // must
ch=ba.data();
第3,4行要分开写,str.toLatin1().data()可能会出错
qstring包含中文时,转换为char*会乱码
解决办法:
1.添加GBK编码支持
#include
QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
然后把第三行的toLatin1换成toLocal8Bit
2.先将 QString 转为标准库中的 string 类型,然后将 string 转为 char *
QString filename;
std::string str = filename.toStdString();
const char* ch = str.c_str();
char*转换为QString
用构造函数直接实现,支持多种类型,以下是构造函数:
QString转const char*
//方法1
QString str1= "Hello , world !";
QByteArray ba = str1.toLocal8Bit();
const char *c1 = ba.data();
const char *c2 = ba.constData();
const char *c3 = str1.toLocal8Bit().constData()
//方法2
QString str1= "Hello , world !";
const char *c= str1.toStdString().c_str();
//方法3,使用strcpy或者memcpy,这里只用memcpy写示例
char test[64] ={0};
QString str1= "Hello , world !";
memcpy(test, str1.toLatin1().data(), strlen(str1.toLatin1().data()));
//如果是中文应该尝试用以下方法:
memcpy(test, str1.toLocal8Bit().data(), strlen(str1.toLocal8Bit().data())); //gb2312
memcpy(test, str1.toUtf8().data(), strlen(str1.toUtf8().data())); //utf-8
const char* 转QString
const char * c = "hello , world !";
QString str1(c);
QString str2 = QString(c);
QString str3 = QString(QLatin1String(c));
QString str4 = QString::fromLocal8Bit(c);
string 转const char*
QString s1;
const char * str = s1.c_str();
const char* 转char*
void main() {
const char* ch = "BDEF";
char *sh = const_cast<char *>(ch);
cout << sh << endl;
sh = const_cast<char*>("faf");
cout << sh << endl;
cout << ch << endl;
system("pause");
}
QByteArray转char*
1.传统方式data和size
QByteArray array(10, 'Q');//初始化
//array 赋值等代码
//...
// 转化
char *buf;//只是一个指针
int len;//buf的长度
buf = array.data();
len = array.size();
2.memcpy
QByteArray array(9,'Q');
char buf[10];//数组
int len_array = array.size();
int len_buf = sizeof(buf);
int len = qMin( len_array, len_buf );
// 转化
memcpy( buf, array, len );
char*转QByteArray
1.利用构造函数
char buf[10];
//给buf赋值
for (int i = 0; i < 10; i++)
{
buf[i] = (i + 1) % 3;//其中存在'\0'元素
}
// 转化
QByteArray array;
array = QByteArray(buf, 10);//因为buf[]中有`\0`,必须要写上数据长度;否则,数据会直接截断,丢失数据
2.memcpy
char buf[10];
//给buf赋值
for (int i = 0; i < 10; i++)
{
buf[i] = (i + 1) % 3;//其中存在'\0'元素
}
// 转化
QByteArray array;
array.resize(sizeof(buf));//重置数据大小
memcpy(array.data(), buf, sizeof(buf));//copy数据

1203

被折叠的 条评论
为什么被折叠?



