Converting QString to Ascii value & Vice Versa in Qt

回眸只為那壹抹淺笑 提交于 2021-02-04 15:52:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!