在 Qt 中使用 QUdpSocket 将 Union 转换为 QByteArray,反之亦然

Convert Union to QByteArray and vice-versa using QUdpSocket in Qt

我有一个联盟如下

#define no_of_bits 240
#define word_size 16

struct bits
{
    unsigned short int bit1:1;
    unsigned short int bit2:1;
    unsigned short int bit3:1;
    unsigned short int bit4:1;
    unsigned short int bit5:1;
    unsigned short int bit6:1;
    unsigned short int bit7:1;
    unsigned short int bit8:1;
    unsigned short int bit9:1;
    unsigned short int bit10:1;
    unsigned short int bit11:1;
    unsigned short int bit12:1;
    unsigned short int bit13:1;
    unsigned short int bit14:1;
    unsigned short int bit15:1;
    unsigned short int bit16:1;
};

union myData
{
        unsigned short int data[no_of_bits/word_size];
        struct bits word[no_of_bits/word_size];
};

我想将 myData union 转换为 QByteArray 以便我可以使用 QUdpSocket 使用 writeDatagram() 函数通过套接字发送它。 所以首先告诉我如何将其转换为 QByteArray.

接下来的事情是,在接收方,我怎样才能将 QByteArray 再次转换为 this Union myData

使用QByteArray构造函数或QByteArray::fromRawData.

请参阅将 转换为 QByteArray 的示例:

#include <QCoreApplication>
#include <QByteArray>


#define no_of_bits 240
#define word_size 16

struct bits
{
    unsigned short int bit1:1;
    unsigned short int bit2:1;
    unsigned short int bit3:1;
    unsigned short int bit4:1;
    unsigned short int bit5:1;
    unsigned short int bit6:1;
    unsigned short int bit7:1;
    unsigned short int bit8:1;
    unsigned short int bit9:1;
    unsigned short int bit10:1;
    unsigned short int bit11:1;
    unsigned short int bit12:1;
    unsigned short int bit13:1;
    unsigned short int bit14:1;
    unsigned short int bit15:1;
    unsigned short int bit16:1;
};

union myData
{
        unsigned short int data[no_of_bits/word_size];
        struct bits word[no_of_bits/word_size];
};



int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    myData data;

    // Variant 1  (no copy data)
    auto byteArray = QByteArray::fromRawData(reinterpret_cast<const char*>(&data), sizeof(data));

    // Variant 2  (copy data)
    QByteArray byteArray2(reinterpret_cast<const char*>(&data), sizeof(data));

    return a.exec();
}

从 QByteArray 转换 :

assert(byteArray.size() == sizeof(data));
memcpy(&data, byteArray.data(), sizeof(data)); // Copy

// OR

assert(byteArray.size() == sizeof(data));
myData* data2 = reinterpret_cast<myData*>(byteArray.data()); // No copy

其实可以直接调用writeDatagram:

QUdpSocket socket;
socket.writeDatagram(reinterpret_cast<const char*>(&data), sizeof(data), QHostAddress("127.0.0.1"), 1234);