Nominate our 2022 Qt Champions!

How to get non null terminated data out of a QByteArray ?

  • Hello!

    I'm trying to serialize a struct and send it over the network using QTcpsocket. I've run into a problem where I can't figure out how to extract raw data out of a QBytearray instance.

    Here's a struct defenition:

    typedef struct __attribute__((packed, aligned(4)))
        quint16 checksum1;
        quint16 checksum2;

    And this is my test case:

        MyStruct sendingStruct;
        sendingStruct.checksum1 = 25;
        sendingStruct.checksum2 = 34;
        char b[sizeof(sendingStruct)];
        memcpy(b,&sendingStruct,sizeof(sendingStruct)); //b="\031\000"\000" after memcpy (in debugger)
        QByteArray ba = QByteArray::fromRawData(b,sizeof(b)); //ba="\031\000"\000" (in debugger)
        char *c =; // c= "\031" (in debugger)  <= **The problem is here**
        MyStruct receivingStruct;
        memcpy(&receivingStruct, &c, sizeof(receivingStruct));
        qDebug() << QObject::tr("receivingStruct.checksum1 = %1, receivingStruct.checksum2 = %2").arg(receivingStruct.checksum1).arg(receivingStruct.checksum2);
        // output receivingStruct.checksum1 = 65108, receivingStruct.checksum2 = 121

    How can I get the raw data from QByteArray without it terminating at the first null character it sees?

  • @Curtwagner1984 said in How to get non null terminated data out of a QByteArray ?:

    <= **The problem is here**

    No it's not, it's here: memcpy(&receivingStruct, &c, sizeof(receivingStruct)); change &c to c or ba.constData(). &c is of type char**

  • @VRonin Indeed! Thank you!

Log in to reply