开发的一个项目中,用到从sqlite3数据库取出的数据,以gdk或ascii格式发送给下游设备。
需要将带有中文的qstring类型转换为char数组。
char chaddress[16];
qstring dd=qlatin1string("1.1 地址位置定义");
memcpy(chaddress,dd.tolatin1().data(),16);
可实现最终输出的chaddress为ascii编码
但问题在于数据库取出的数据格式为qvariant,qvariant可转换为qstring,但不可以之间转换为char*类型。而且qlatin1string中参数不能为qstring,可传递char*类型。
在多次尝试后,最后的方法为:
qtextcodec *utf8 = qtextcodec::codecforname("utf-8");
qtextcodec* gbk = qtextcodec::codecforname("gbk");
//_querysql为qsqlquery* _querysql;
qstring str1=_querysql->value(fieldno++).tostring();//将数据库查出的数据转换为qstring类型
qstring strunicode= utf8->tounicode(str1.tolocal8bit().data());//将str1从utf8 -> unicode
qbytearray gb_bytes= gbk->fromunicode(strunicode);//unicode -> gbk, 得到qbytearray
char inaddress[16];
memcpy(inaddress,gb_bytes,16);//得到char数组格式gdk编码的数据
发表评论