Qt中的QString与int、const char *、ASCII码互相转换

作者:billy
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处

1. QString 转 int

bool ok;
QString str1 = "0xf8";
int value1 = str1.toInt(&ok, 16);
qDebug() << ok << " " << value1;    // true 248

QString str2 = "012";
int value2 = str2.toInt(&ok, 10);
qDebug() << ok << " " << value2;    // true 12

QString str3 = "a";
int value3 = str3.toInt(&ok, 10);
qDebug() << ok << " " << value3;    // false 0

2. int 转 QString

int a = 5;
qDebug() << QString::number(a, 10);	// "5"

double b = 1.2;
QString str;
str.setNum(b);
qDebug() << str;	// "1.2"

3. QString 转 const char *

QString str = "abc";

QByteArray array = str.toLatin1();
const char *ch1 = array.data();
qDebug() << ch1;	// "abc"

std::string s = str.toStdString();
const char *ch2 = s.c_str();
qDebug() << ch2;	// "abc"

4. const char * 转 QString

const char *ch = "hello world !";

QString str1 = QString::fromLocal8Bit(ch);
qDebug() << str1;	// "hello world !"

QString str2(ch);
qDebug() << str2;	// "hello world !"

5. const char * 转 unsigned char *

const char *ch = "hello world !";
unsigned char *ret = (unsigned char *)ch;

6. const unsigned char * 转 QString

const unsigned char str[5] = {'t', 'e', 's', 't'};
string s = (char *)str;
qDebug() << QString::fromStdString(s);

7. QString 转 ASCII码

QString str = "abcde";
QByteArray array = str.toLatin1();

for (int i = 0; i < array.size(); ++i)
{
    qDebug() << (int)array.at(i);	// 97 98 99 100 101
}

8. ASCII码 转 QString

QByteArray array;
array.append(97);
array.append(102);
array.append(108);
array.append(116);

for (int i = 0; i < array.size(); ++i)
{
    qDebug() << QChar(array.at(i));	// 'a' 'f' 'l'  't'
}

9. 发送ASCII码的控制字符

char cSTX = 0x02;					// STX
char cETX = 0x03;					// ETX
char codeSend = 0x08;				// Code

QString ident = "1001";				// Control code character
QString function = "000A";			// Transmission data length
QString content = "CONNECT_PC";		// Data
QString validation = "869d";		// CRC 16 
QString data = ident + function + content + validation;

QString result;
result.sprintf("%c%c%s%c", cSTX, codeSend, data.toLatin1().data(), cETX);

QString temp = QString(cSTX) + QString(codeSend) + data + QString(cETX);
result.sprintf("%s", temp.toLatin1().data());

// result: 1001000ACONNECT_PC869d

在这里插入图片描述

你可能感兴趣的:(Qt,Qt,ASCII,类型转换)