1、QString转换成十六进制
QT开发交流+赀料君羊:661714027
QT开发交流+赀料君羊:661714027
void ConvertQStringToHex(const QString &str,const QByteArray& byte)
{
int hexData,lowhexData;
int hexdataLen=0;
int len = str.length();
byte.resize(len/2);
char lstr,hstr;
for(int i=0;i<len;)
{
hstr = str[i].toLatin1();
if(hstr ==' ')
{
i++;
continue;
}
i++;
if(i>=len)
{
break;
}
lstr = str[i].toLatin1();
hexData = ConvertCharToHex(hstr);
lowhexData = ConvertCharToHex(lstr);
if((hexData == 16)|| (lowhexData==16))
{
break;
}
else
{
hexData = hexData*16+lowhexData;
}
i++;
byte[hexdatalen] = (char)hexData;
hexdataLen++;
}
byte.resize(hexdataLen);
}
2、char转十六进制
char ConvertCharToHex(char ch)
{
if((ch >= '0') && (ch <= '9'))
return ch-0x30;
else if((ch >= 'A') && (ch <= 'F'))
return ch-'A'+10;
else if((ch >= 'a') && (ch <= 'f'))
return ch-'a'+10;
else return (-1);
}
3、QByteArray转QString
QByteArray array("Hello World");
QString str = array;
或
str.prepend(array);
4、将16进制QString转换成QByteArray
QByteArray HexStringToByteArray(QString HexString)
{
bool ok;
QByteArray ret;
HexString = HexString.trimmed();
HexString = HexString.simplified();
QStringList sl = HexString.split(" ");
foreach (QString s, sl) {
if(!s.isEmpty())
{
char c = s.toInt(&ok,16)&0xFF;
if(ok)
{
ret.append(c);
}
else
{ }
}
}
return ret;
}
5、QByteArray转16进制QString
QString MainWindow::ByteArrayToHexString(QByteArray data)
{
QString ret(data.toHex().toUpper());
int len = ret.length()/2;
qDebug()<<len;
for(int i=1;i<len;i++)
{
ret.insert(2*i+i-1," ");
}
return ret;
}
原文作者:临渊慎行
原文地址:https://blog.csdn.net/zq9955/article/details/127045261