数据之间的转换
1、QString转const char*
1.1//不带中文
QString str1 = "Test";
QByteArray ba = str1.toLatin1();
const char *c_str2 = ba.data();
printf("str2: %s", c_str2);
1.2//带中文,第五一样
char a[20];
QString str = “你好”;
QByteArray ba = str .toLocal8Bit();//线路
memcpy(a, ba.data(), ba.size());
2、unsigned char* 转char*
unsigned char* p;
char *q=(unsigned char*)p
3、QByteArray ba{0x00,0x01,0x02},打印出“000102”
QString str = ba.toHex();
4、char data[4] = {0x01,0x02,0x03,0x04},打印出“01020304”
QByteArray ba(data,4);
QString str = ba.toHex();
5、中文字符串转char
QString str = “你好”;
QByteArray ba = str.toLocal8Bit();
char* dataChar;
dataChar = ba.data();
6、带有中文的char*或者QByteArray转QString
6.1
QByteArray ba = "你好";
QString str = QString::fromLocal8Bit(ba);
ps:QByteArray::resize为0之后,不会影响后续初始化,如下程序能正常打印字符串。
QByteArray ba;
ba.resize(0);
ba[0]=0x54;
ba[1]=0x65;
ba[2]=0x73;
ba[3]=0x74;
ba[4]=0x21;
qDebug()<<ba;
6.2
char ch[4];
ch[0] = 0xC4;
ch[1] = 0xE3;
ch[2] = 0xBA;
ch[3] = 0xC3;
QByteArray ba;ba.resize(4);//一定要这个resize
memcpy(ba.data(),ch,4);
QString str = QString::fromLocal8Bit(ba);
qDebug()<<str;//你好
6.3
#include <QTextCodec>
QTextCodec::codecForName("GBK")->toUnicode(ba);
7、有0x00的char*转QString
info[3]={0x01,0x00,0x02};
QString tempStr="";int j=0;
for(int i=0;i<3;i++)
{
tempStr += QString("%1 ").arg(info[j++]&0xFF,2,16,QLatin1Char('0'));//如果不与上0xFF,结果会出问题
}
return tempStr.toUpper();
8、QString str=“54 65 73 74 21” 转 QByteArray ba ={0x54,0x65....}
1、QByteArray ba1 = str.toLatin1();或者QByteArray ba1 = str.toUtf8();
2、QByteArray ba2 = QByteArray::fromHex(ba1);
ps:即使str里面有“00”依旧可以转换
9、QString转char*
str.toStdString().c_str;
10、十六进制QString转float或者double
11、QString保留小数
QString::number(100.1002121323,'f',6) ;
长风破浪会有时,直挂云帆济沧海!
可通过下方链接找到博主
https://www.cnblogs.com/judes/p/10875138.html