Qt C++ QString to QByteArray Conversion
Solution 1
I guess you should use:
QString::fromUtf8(const QByteArray &str)
Or:
QString::QString(const QByteArray &ba)
to convert QByteArray to QString, then write it into file by QTextStream.
After that, read file by QTextStream, use:
QString::toUtf8()
to convert QString to QByteArray.
QString::QString(const QByteArray &ba)
Constructs a string initialized with the byte array ba. The given byte array is converted to Unicode using fromUtf8().
P.S:
Maybe use QFile::write and QFile::read is a better way.
Solution 2
try using toLocal8Bit() .. it works fine with me
Solution 3
There's a simple way :
QByteArray ba;
QString qs = "String";
ba += qs;
More hard way:
QByteArray ba;
QDataStream in(&ba, QIODevice::WriteOnly);
in << QString("String");
Extreme way, for people who want to use QBuffer:
#include <QDebug>
#include <QBuffer>
#include <QDataStream>
#include <QIODevice>
#include <QByteArray>
#include <QString>
#include <qcoreapplication.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QByteArray byteArray;
QBuffer buffer(&byteArray);
buffer.open(QIODevice::ReadWrite);
QDataStream in( &buffer );
in << QString("String");
buffer.close();
for (int i = 0; i < byteArray.length(); ++i) {
printf("%c - %x\n", byteArray.at(i), byteArray.at(i));
}
printf("\n");
return a.exec();
}
Who run last code can ask me where does the null byte come from?
QDataStream
serializes the QString
as a little-endian. 4 bytes are read to create the 32-bit length value, followed by the string itself in UTF-16. This string length in UTF-16 is 12 bytes, so the first three bytes in QByteArray
will be zero.
There is often a problem with reading the QByteArray
in qDebug ()
The recording is fine.
Don't forget to remove QT_NO_CAST_FROM_BYTEARRAY
in your .pro
file, if it has

James
Updated on October 23, 2021Comments
-
James over 1 year
I have created an encrypt/decrypt program, when encrypting I store the encrypted QByteArray in a text file.
When trying to decrypt I retrieved it and then put it into the decryption method, the problem is that I need a way to convert it to QByteArray without changing the format, otherwise it will not decrypt properly. What I mean is if the file gave me an encrypted value of 1234 and I converted that to QByteArray by going
1234.toLatin1()
it changes the value and the decryption does not work. Any suggestions?My Code:
QFile file(filename); QString encrypted; QString content; if (file.open(QIODevice::ReadOnly)) { QTextStream stream( &file ); content = stream.readAll(); } encrypted = content.replace("\n", ""); qDebug() << encrypted; // Returns correct encrypted value QByteArray a; a += encrypted; qDebug() << "2 " + a; // Returns different value than previous qDebug() QByteArray decrypted = crypto.Decrypt(a, key); return decrypted;