Search code examples
qtreinterpret-castqbytearray

How to convert double* data to const char* or QByteArray efficiently


I am trying to use the network programming APIs in Qt in my project. One part of my code requires me to convert double* data to QByteArray or a const char*.

I searched through the stackoverflow questions and could find many people suggesting this code :

QByteArray array(reinterpret_cast<const char*>(data), sizeof(double));

or, for an array of double :

QByteArray::fromRawData(reinterpret_cast<const char*>(data),s*sizeof(double));

When I use them in my function, It does notgive me the desired result. The output seems to be random characters.

Please Suggest an efficient way to implement it in Qt. Thank you very much for your time.

Regards Alok


Solution

  • If you just need to encode and decode a double into a byte array, this works:

    double value = 3.14159275;
    // Encode the value into the byte array
    QByteArray byteArray(reinterpret_cast<const char*>(&value), sizeof(double));
    
    // Decode the value
    double outValue;
    // Copy the data from the byte array into the double
    memcpy(&outValue, byteArray.data(), sizeof(double));
    printf("%f", outValue);
    

    However, that is not the best way to send data over the network, as it will depend on the platform specifics of how the machines encode the double type. I would recommend you look at the QDataStream class, which allows you to do this:

    double value = 3.14159275;
    // Encode the value into the byte array
    QByteArray byteArray;
    QDataStream stream(&byteArray, QIODevice::WriteOnly);
    stream << value;
    
    // Decode the value
    double outValue;
    QDataStream readStream(&byteArray, QIODevice::ReadOnly);
    readStream >> outValue;
    printf("%f", outValue);
    

    This is now platform independent, and the stream operators make it very convenient and easy to read.