Initialize union with array? I want to create a datastructure for network communication (TCP),  where I can build up a byte array from small tagged pieces (like in serialized class). And of course I need a reverse behavior of this, I need a pieces from a byte array that is why a I put a constructor to the union.

typedef union message {

    struct {
        int header;
        int payload;
    } pieces;
    int whole[2];

    message (int* arr) {
        for (int i = 0; i &lt; 2; i++) {
            whole[i] = arr[i];
        }
    }
    message ():iVal(){}
} Message ;

main() {
    int a[2] = {10, 2};
    Message msg(a);
}


This snippet is working. I'm just curious is there any other or better solution?
An old trick is to cast a pointer to an array of bytes to an pointer of a struct (POD) with the exact memory layout of the final message(s).

struct Message {
    int header;
    int payload;
};

// parsing bytes -&gt; messages
char buffer[SIZE];
recv(buffer, 0, SIZE); // replace with actual code for receiving
Message *messages = reinterpret_cast&lt;Message *&gt;(buffer);
size_t max_message_count = SIZE * sizeof(char) / sizeof(Message);


// converting messages -&gt; byte array
Message messages[MSG_COUNT];
// initialize messages
char *bytes = reinterpret_cast&lt;char *&gt;(messages);
size_t byte_count = MSG_COUNT * sizeof(Message) / sizeof(char);


However, this requires a strict memory mapping between the message struct and the serialized byte format (so Message in this case has to be a POD struct). Yes, this effectively bypasses the type system, but if used properly its the fastest way of parsing messages (and in case of embedded systems the reuse of the memory is a nice touch).