Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Qt C++) Write QString to file as Binary

I am working on a project and I need to write (and in the future read) a string (QString) as binary. The string is in HEX format, like this "00010203040506070a0f01" etc...

I got this far through a tutorial on YouTube:

void Output()
{
    QString ye("01020a");
    QFile file("C:\\Users\\Public\\Documents\\Qt_Projects\\myfile.dat";

    if(!file.open(QIODevice::WriteOnly))
    {
        qDebug() << "Could not open file to be written";
        return;
    }

    QDataStream out(&file);
    out.setVersion(QDataStream::Qt_5_0);

    out << ye;

    file.flush();
    file.close();
   }

But when I open "myfile.dat" with a hex editor, the hex values are different, the QString "ye" was written to the text side of things.

00 00 00 0C 00 30 00 31 00 30 00 32 00 30 00 61

Help?

like image 860
mrg95 Avatar asked Jul 18 '26 07:07

mrg95


1 Answers

You should convert it before writing.

QByteArray array = QByteArray::fromHex(ye.toLatin1());
file.write(array);

You don't need to use QDataStream since you already have QByteArray and can write it directly.

You can read and convert the data back to hex representation as follows:

QString s = file.readAll().toHex();
like image 123
Pavel Strakhov Avatar answered Jul 20 '26 21:07

Pavel Strakhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!