Important: Please read the 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];

  • Lifetime Qt Champion

    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 (
    const QByteArray archvio = file.readAll();
    const double*datos = reinterpret_cast<const double*>(;

    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*>(; // error: reinterpret_cast from type 'const char*' to type 'double*' casts away qualifiers
      //   const char *datos = reinterpret_cast<double*>(;

  • Lifetime Qt Champion

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

    const char *datos = reinterpret_cast<double*>(;

    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.


  • @aha_1980
    Thanks! it works with your solution!

Log in to reply