Search code examples
qtqbytearray

QByteArray to int always give 0


I try to send data throw qtcpsocket and use QByteArray. I send previosly size of data and try convert to int like this QByteArray to Int conversion. But always get 0. Code convertion example:

QString ss = "bca";
int aaa;
QByteArray b;
QDataStream stream(&b, QIODevice::ReadWrite);

stream << ss.toUtf8().size();
stream >> aaa;

In this example aaa is always 0, but ss.toUtf8().size() isnt. What im doing wrong?


Solution

  • QString ss = "bca";
    int aaa;
    QByteArray b;
    QDataStream stream(&b, QIODevice::ReadWrite);
    
    stream << ss.toUtf8().size();
    stream.device().seek(0); // add this code
    stream >> aaa;
    

    The inner pointer of QByteArray is at the end, so nothing can be read.