How to get a QByteArray from a QString?

Viewed 6456

I am trying to understand how QByteArray and QString work together in Qt. I am using Qt 5.9.

I have the following case where I create a QByteArray in memory.

QByteArray qba;
quint8 version = 1;
qba << version;
quint8 type = 122;
qba << type;

qDebug() << qba.length() << " " << QString(qba);

The debug statement prints:

2   "\u0001z"

So, I have 2 bytes of data and the string representation is extracted.

Now, what I want to do is start with the string representation (which is given to me as a raw C++ char array) and create the QByteArray representation. So, I create the array as follows:

char msg[] = { '\\', 'u', '0', '0', '0', '1', 'z', '\0' };
QString testStr = QString::fromUtf8(msg);
QByteArray testRaw = testStr.toUtf8();
qDebug() << testRaw.length() << " " << QString(testRaw);

Now this prints:

7   "\\u0001z"

I am not sure how I can start from such a character array and get the byte array representation. I am not sure if this is a string encoding issue but I could not recreate this binary representation regardless of which String method I tried (fromLatin1, fromUtf16 etc.)

1 Answers

Conversion between QString and QByteArray is encoding depended! Your QString(qba) assumes that data are UTF-8 encoded, see QString documentation.

In other direction you have:

Ans so on, there are also vice versa static methods.


Note that qDebug() << anyString; doesn't print data literally but in form for developer, that is why it is surrounded with quotes and unprintable character was converted to "\u0001"


QByteArray qba;
quint8 version = 1;
qba << version;
quint8 type = 122;
qba << type;

// character '\1' is not printable, so qDebug do a developer friendly conversion 
qDebug() << qba.length() << " " << QString(qba);

// to revert conversion, you code should look like this:
QString convnerted(qba);
QByteArray reverted = convnerted.toUtf8();

Q_ASSERT(reverted == qba);
Related