4

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(" ");
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
zhanfeng
  • 43
  • 1
  • 1
  • 3

2 Answers2

0

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
Fritz
  • 359
  • 3
  • 9
0

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"
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Since the question specifically mentions ASCII encoding, `QString::toLatin1()` would make more sense than `QString::toLocal8Bit()` in this case. – MrEricSir Aug 20 '17 at 00:05