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

binary, c++, file-io, hex, qt

Solution

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();

Problem

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?

Original source