问题
I have a QString StrData = "abcd"
and I want get the Ascii
value in hex of that string and Vice Versa.
For example from "abcd" to "61 62 63 64"
and from "61 62 63 64" to "abcd"
I manage to get the Ascii value in hex but don't know how to get it back
Qstring StrData = "abcd";
Qstring HexStrData;
for (int i = 0; i < StrData.length(); i++) {
HexStrData.append(Qstring::number(StrData.at(i).unicode(), 16));
HexStrData.append(" ");
}
回答1:
To do the first conversion you can use the following method:
QString StrData = "abcd";
qDebug()<<"before "<< StrData;
QStringList numberString;
for(const auto character: StrData){
numberString << QString::number(character.unicode(), 16);
}
QString HexStrData= numberString.join(" ");
qDebug()<<HexStrData;
For the second case is much simpler as I show below:
QString str = QByteArray::fromHex(HexStrData.remove(" ").toLocal8Bit());
qDebug()<<str;
Output:
before "abcd"
"61 62 63 64"
"abcd"
回答2:
Example
QString hex("0123456789ABCDEF");
QString strStr("abcd");
QString hexStr;
for (int ii(0); ii < strStr.length(); ii++)
{
hexStr.append(hex.at(strStr.at(ii).toLatin1() >> 4));
hexStr.append(hex.at(strStr.at(ii).toLatin1() & 0x0F));
}
qDebug() << hexStr;
QByteArray oldStr = QByteArray::fromHex(hexStr.toLocal8Bit());
qDebug() << oldStr.data();
Shows:
"61626364"
abcd
来源:https://stackoverflow.com/questions/45772951/converting-qstring-to-ascii-value-vice-versa-in-qt