c++qtqvectorqdatastream

QDataStream read to QVector


I have a QByteArray containing 8 bits representing two floating-point numbers, what is the correct and simplest way to read QDataStream to QVector<float>?

Code:

QByteArray ByteFloatArray;
QVector<float> qVecfloat;
ByteFloatArray.append(0x41);
ByteFloatArray.append(0x31);
ByteFloatArray.append(0x99);
ByteFloatArray.append(0x9A);  // 4 bits float == 11.1

ByteFloatArray.append(0x41);
ByteFloatArray.append(0x31);
ByteFloatArray.append(0x99);
ByteFloatArray.append(0x9A);  // 4 bits float == 11.1

QDataStream myStream(ByteFloatArray);
myStream.setFloatingPointPrecision(QDataStream::SinglePrecision);
myStream >> qVecfloat;

Code above gives:

STD:: bad_alloc at memory location"

I have read related problems, but I can't understand them properly to implement it in my case.

Below is my current solution, but I think it is over complicated and there is a simpler way to do that:

QVector<float> qVecfloat;
float myFloat;
for (int i = 0; i < 2; i++) {       
    QDataStream myStream(ByteFloatArray);
    myStream.setFloatingPointPrecision(QDataStream::SinglePrecision);
    myStream >> myFloat;
    qVecfloat.append(myFloat);
    ByteFloatArray.remove(0, 4);
    qDebug() << "size " << qVecfloat.size() << " : " << qVecfloat;
}

Solution

  • You can use QDataStream::atEnd() in a loop and read the float data like this :

    QDataStream myStream( ByteFloatArray );
    myStream.setFloatingPointPrecision( QDataStream::SinglePrecision );
    
    float f = 0.0f;
    while ( !myStream.atEnd() )
    {
        myStream >> f;
        qVecfloat.append( f );
    }
    
    qDebug() << qVecfloat;
    

    Output:

    QVector(11.1, 11.1)