龙空技术网

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

QT高级进阶 197

前言:

当前大家对“c语言intstring”大致比较看重,你们都需要了解一些“c语言intstring”的相关知识。那么小编也在网摘上搜集了一些关于“c语言intstring””的相关知识,希望小伙伴们能喜欢,朋友们快快来学习一下吧!

1、QString 转 int

bool ok;QString str1 = "0xf8";int value1 = str1.toInt(&ok, 16);qDebug() << ok << " " << value1;    // true 248QString str2 = "012";int value2 = str2.toInt(&ok, 10);qDebug() << ok << " " << value2;    // true 12QString 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

QT开发交流+赀料君羊:714620761

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;					// STXchar cETX = 0x03;					// ETXchar codeSend = 0x08;				// CodeQString ident = "1001";				// Control code characterQString function = "000A";			// Transmission data lengthQString content = "CONNECT_PC";		// DataQString 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

标签: #c语言intstring #jquery转义ascii #c语言int转字符串 #javaascii码转换 #javachar转ascii码