Qt C++ QString to QByteArray Conversion

James picture James · Jun 14, 2016 · Viewed 68.8k times · Source

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;

Answer

Daniel picture Daniel · Jun 14, 2016

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.