2

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?

3 Answers 3

8

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();
Sign up to request clarification or add additional context in comments.

5 Comments

Worked like a charm :) Thx I need to wait 4 min before accepting
Just wondering, how would I go about reading a file to a QString? I'm assuming a variation of this, but anything I'm missing?
Do you mean converting it back to hex representation? QString s = file.readAll().toHex();
Perhaps, what is the easiest way to print the string? I'm very new to qt. Im messing with qDebug but I don't know where it displays
Yes it worked :) I foudn the App Output and everything is perfect!
1

in QString each character occupy 2 bytes (Using unicode). You can consult the ascii table to search a character's code value in hex int:

'0': 0x30
'1': 0x31
'a': 0x61

so for the string "01020a" its ascii code sequence is: 00 30 00 31 00 30 00 32 00 30 00 61

"00 00 00 0C": I think it's the type identify for QString.

Sorry for my poor expression, hope it's useful.

Comments

0

Saving QString to QFile;

QString qStr="abc";
qFile.write(qStr.toUtf8().constData());

conversion sequences are here;
   QString => QByteArray => const char* => QFile.write()

[ref class function]

QByteArray QString::toUtf8() const;
const char * QByteArray::constData() const;
qint64 QIODevice::write(const char * data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.