Send and Receive Double Array (double * ) over QTcpSocket



  • In QT C++ I can send packet over QTcpSocket by using QDataStream for double, int , QString.. data types. But I want to send array of doubles by using QDataStream. My double array function in shown in this code block.

    double * array = generatePacketDoubleArray(1,10,0.001);
    

    Generate Double Array Function :

    double * Producer::generatePacketDoubleArray(int packetNum,int maxlen,double stepDouble)
    {
        double *array = new double[maxlen];
    
        double increase = 0;
    
        for(int i=0;i<maxlen;++i)
        {
            increase += stepDouble;
            array[i] = stepDouble*maxlen*packetNum+increase;
        }
        return array;
    }
    

    I want to send my double array packet same as this code blocks by using QDataStream in Server Side and Receive double * from QDataStream in Client Side . But I could not find a solution for cast double * to QByteArray . I want to learn this cast operation.

    Regards..

            QByteArray block;
            QDataStream out(&block, QIODevice::WriteOnly);
            out.setVersion(QDataStream::Qt_4_0);
    
            out << static_cast<qint32>(packet.packetNum)
                << static_cast<qint32>(packet.data)
                << static_cast<qint32>(packet.packetSize);
    


  • @Ayse

    I found solution ;

    In Server Side :

            doubleArray = generatePacketDoubleArray(counter,maxlen,0.001);
            Packet packet(counter,doubleArray);
    
            QByteArray block;
            QDataStream out(&block, QIODevice::WriteOnly);
            out.setVersion(QDataStream::Qt_4_0);
    
            out << static_cast<qint32>(packet.packetNum)
                << QByteArray::fromRawData(reinterpret_cast<const char*>(packet.doubleArrayData),maxlen*sizeof(double));
    
            qDebug() << "Packet Num : " << counter << " Bytes Written -> " << tcpServerConnection->write(block);
    
            tcpServerConnection->waitForBytesWritten();
    
    

    In Client Side :

            qint32 packetNum ;
            QByteArray byteArray;
    
            in >>packetNum >> byteArray;
    
            qDebug() << "Packet Num : " <<packetNum;
    
            double doubleArray[maxlen];
            memcpy(doubleArray, byteArray.data(),byteArray.count());
    
            for(int i = 0;i<maxlen;i++)
                printf("%f   ",doubleArray[i]);
            printf("\n");
    
    


  • @Ayse, Great recovery! I was looking at your first post and saying... how do I read the array when I don't know how long it is! :D


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.