3

I'm working with a buffer and I'm trying to get a string from it, but isnt working...

Example:

*void myFunc(QDataStream& in)
{
    quint8 v;
    in >> v;
    // Ok, I caught v value successfuly
    QString s;
    in >> s;
    // Didnt work :<
}*

The string lenght is stored on 2 first bytes...

Thanks

Kraup Kywpz
  • 43
  • 1
  • 1
  • 6
  • 3
    That looks ok to me. What does the code doing the writing look like? – cgmb Sep 19 '12 at 19:22
  • 1
    The buffer is storing alot of things, when I try to extract a string from it, the position didnt jump to the next opcode – Kraup Kywpz Sep 19 '12 at 19:23
  • 1
    How do you write the string to the buffer in the first place ? What do you mean by "The string length is stored on 2 first bytes" ? (Because a `QString` is stored and read as a 32-bit value followed by the actual UTF16 string). – alexisdm Sep 19 '12 at 20:09
  • 2
    I mean I'm trying to read a binary file that I don't write, in this case the string is stored with U16(lenght) followed by it content... – Kraup Kywpz Sep 19 '12 at 20:29

2 Answers2

2

If the string was not written as a QString, you need to read its length and content separately.

quint8 v;
in >> v;

quint16 length = 0;
in >> length;

// the string is probably utf8 or latin
QByteArray buffer(length, Qt::Uninitialized);

in.readRawData(buffer.data(), length); 
QString string(buffer);

You might have to change the endianness of the QDataStream with QDataStream::setByteOrder before reading the 16-bit length.

alexisdm
  • 29,448
  • 6
  • 64
  • 99
0

We should really see the writing code and how you create the QDataStream. I tried with the following sample, and in this case your function works very well:

#include <QCoreApplication>
#include <QDebug>
#include <QDataStream>
#include <QBuffer>

void myFunc(QDataStream& in)
{
    quint8 v;
    in >> v;
qDebug() << v;
    // Ok, I caught v value successfuly
    QString s;
    in >> s;
qDebug() << s;
    // Didnt work :<
}


int main(int argc, char ** argv) {
    QCoreApplication a(argc, argv);

    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);


    // write test data into the buffer
    QDataStream out(&buffer);
    quint8 ival = 42;
    QString sval = "Qt";
    out << ival;
    out << sval;

    // read back data
    buffer.seek(0);
    myFunc(out);

    return a.exec();
}

Output when executed:

$ ./App 
42 
"Qt" 
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123