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

11,510

Solution 1

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

Solution 2

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.

Share:
11,510
mrg95
Author by

mrg95

Updated on June 04, 2022

Comments

  • mrg95
    mrg95 almost 2 years

    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?

  • mrg95
    mrg95 almost 11 years
    Worked like a charm :) Thx I need to wait 4 min before accepting
  • mrg95
    mrg95 almost 11 years
    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?
  • Pavel Strakhov
    Pavel Strakhov almost 11 years
    Do you mean converting it back to hex representation? QString s = file.readAll().toHex();
  • mrg95
    mrg95 almost 11 years
    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
  • mrg95
    mrg95 almost 11 years
    Yes it worked :) I foudn the App Output and everything is perfect!