qt常用数据类型转换

1、int转QString

quint8转QString

quint8 k = 77;
QString str_1;
str_1 = QString::number(k, 10);
qDebug() << str_1;      // "77"
QString str_2 = QString("%1").arg(k);
qDebug() << str_2;      // "77"

2、quint8转QByteArray

QByteArray all;
quint8 head = 0XFF;
all.append(head);
qDebug() << all;    //"\xFF"

3、quint8转QByteArray再转quint8

QByteArray all;
quint8 head = 65;
all.append(head);
qDebug() << all;    //"A" // 可以看出是ascii码的值,65对应A
QByteArray temp = all.mid(0, 1);
qDebug() << temp;   //"A"
char* data = temp.data();
qDebug() << data;   //A
quint8 i = (quint8) data[0];
qDebug() << i;      //65

4、QByteArray转char*

QByteArray b("123");
qDebug() << b;      //"123"
char* d = b.data();
qDebug() << d;      //123

5、quint8转QByteArray(感觉QByteArray.toInt()等方法很不好用。。)

quint8 q = 65;
QByteArray b;
b.setNum(q, 10);
qDebug() << b;  //"65"
qDebug() << "int:" << b.toInt() << " hex:" << b.toHex();    //int: 65  hex: "3635" 
// int转成功了,但是hex...额,没有看懂

6、QString转char*

QString str("123");
std::string temp = str.toStdString();
const char* constChar = temp.c_str();
char* result = new char[strlen(constChar) + 1];
strcpy(result, constChar);
qDebug() << result;     //123

7、quint16转char*

quint16 code = 9299;
char buff[3];
memcpy(buff,&code,sizeof(quint16));
qDebug() << buff;   //S$

8、char*转quint16

// buff为上一点中的数据
quint16 res = *((quint16*)buff);
qDebug() << res; //9299

9、quint16转QByteArray再转quint16

QByteArray q;
quint16 code = 9299;
char buff[3];
memcpy(buff,&code,sizeof(quint16));//quint16转char*
qDebug() << buff;   //S$

q.append(buff);     //char*转为QByteArray
char *temp = q.data();  // QByteArray转char*

quint16 res = *((quint16*)temp);// char*转quint16
qDebug() << "size:" << q.length() << " byte:" << q << " res:" << res;//size: 2  byte: "S$"  res: 9299

 

持续更新中。。

你可能感兴趣的:(qt常用数据类型转换)