Reputation: 351
If QString str = "0xFFFF"
, how to turn this text representation of an hex into a QByteArray? In the end, I would like to have the same of what I get from the following:
QByteArray ba;
ba.resize(2);
ba[0] = 0xFF;
ba[1] = 0xFF;
Upvotes: 5
Views: 13311
Reputation: 7692
In either case the final QByteArray
would be a sequence of hex values, i.e. FFFF
. Conversion should be applied on that string. Given that, if your input string is provided prepended with the 0x
, you should get rid of it via mid()
.
Here is a code snippet which compares the results of the two approaches: manually filling the QByteArray
with hex values or converting hex values from a QString
:
QByteArray array1;
array1.resize(2);
array1[0] = 0xFF;
array1[1] = 0xFF;
QString str = "0xFFFF";
QString value = str.mid(2); // "FFFF" <- just the hex values!
QByteArray array2 = QByteArray::fromHex(value.toLatin1());
qDebug() << array1; // not printable chars
qDebug() << array2;
qDebug() << array1.toHex(); // to have a printable form use "toHex()"!
qDebug() << array2.toHex();
Upvotes: 5