Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to get a *double from a QByteArray?



  • Hi i'm working with a binary file that contains samples from a dongle in double format. I need those samples in *double because thats the format that my fft needs.
    But the only way that i found to take that samples off is using QByteArray or QDataStream. Can anyone tell me how to do that conversion? I will appreciate any solution.
    Here are my codes:
    First i tried with QByteArray

        QFile file("prueba.bin");
        double *datos = NULL;
        QByteArray archivo(10*sizeof(double), 0);
        archivo = file.readAll();
        memcpy(datos, &archivo , archivo.count()); //shows me error
    

    And here i tried with QDataStream

    QFile file("prueba.bin");
    double *datos = NULL;
    QVector<double> Qdatos(10);
    QDataStream mediator(&file);
    mediator >> Qdatos;
    for(int i=0; i<10 ; i++)
        {
            *(datos + i) = Qdatos[i];
        }

  • Qt Champions 2019

    QDataStream is using an internal Format, it can not be used to read any binary data not created with QDataStream.
    You need to convert them by yourself:

    QFile file("prueba.bin");
    if (file.open(QIODevice::ReadOnly))
      return;
    const QByteArray archvio = file.readAll();
    const double*datos = reinterpret_cast<const double*>(archivo.data());
    

    And you forgot to open your QFile.

    /edit: fixed the const cast



  • @Christian-Ehrlicher
    Thanks for your answer but it still give me an error message.

    const char *datos = reinterpret_cast<double*>(archivo.data()); // error: reinterpret_cast from type 'const char*' to type 'double*' casts away qualifiers
      //   const char *datos = reinterpret_cast<double*>(archivo.data());
                                                                     ^
    

  • Lifetime Qt Champion

    @Pedro1992 said in How to get a *double from a QByteArray?:

    const char *datos = reinterpret_cast<double*>(archivo.data());

    That's obviously wrong.

    1. the result should be const double *
    2. cast toconst double * to fix the error

    const double *datos = reinterpret_cast<const double *>(archivo.constData());

    There are some requirements you have to assure:

    1. the number of byte in archivo.constData() must be a multiple of sizeof(double)
    2. you need to know how many double you can use after the cast (exactly the number of byte in archivo.constData() divided by sizeof(double)
    3. of course the contents in archivo.constData() must be valid double numbers, in the same endianess as your machine where you interpret them

    One more note: archivo.constData() is only valid as long as archivo is valid.

    Regards



  • @aha_1980
    Thanks! it works with your solution!


Log in to reply