kzsnyk
kzsnyk

Reputation: 2211

QByteArray to Int conversion

I am trying to convert a QByteArray into an int with the following code :

int byteArrayToint(const QByteArray &ba, QDataStream::ByteOrder byteOrder)
{
    int val = 0;
    QDataStream stream(ba);
    stream.setByteOrder(byteOrder);
    stream >> val;
    return val;
}

Then in the main function :

    ....
    QByteArray ba;
    ba[0]=0x20;
    ba[1]=0x17;

    for(int i(0); i < ba.size(); i++)
        qInfo() << QString("0x%1").arg((int)ba.at(i), 2, 16);

    qInfo() << "date =" << byteArrayToint(ba, QDataStream::BigEndian);
    ...

And the output is :

"0x20"
"0x17"
date = 0

But if i use QByteArray("Hello") instead of the preivous one it gives the expected result :

"0x48"
"0x65"
"0x6c"
"0x6c"
"0x6f"
date = 1214606444

I cannot find where the mistake is so far. I know methods using bits shifting work well but i would like to understand why i don't get the same result with Qt classes.

Thanks for any help.

Upvotes: 1

Views: 2472

Answers (1)

p-a-o-l-o
p-a-o-l-o

Reputation: 10047

In this line:

stream >> val;

you'reading sizeof(int) bytes from the stream into the variable val.

Given that sizeof(int) is 4, whatever byte array sized at least four bytes is ok to yeld some int value (the remaining bytes will be ignored).

Upvotes: 2

Related Questions