Union and endianness without htonl/ntohl

Viewed 172

I want to parse a header of my TCP package that I receive.

Assume this is a header structure:

(2 bytes for commands) + (2 bytes for token) + (4 bytes for data length)
Example of package: 0x01 0x02 0x12 0x34 0x00 0x00 0x00 0x05
There 0x0102 is command, 0x1234 is token and 0x000005 is data length.

I want to parse this header in effective way on Windows platform. I made the next union for this header:

typedef union
{
    struct
    {
        uint16_t command;
        uint16_t token;
        uint32_t data_length;
    } field;
    char bytes[8];
} MyHeader_t;

MyHeader_t bar;
read_8_bytes(bar.bytes);
std::cout << bar.fields.token << std::endl;

Next I tried to copy package above to my bytes array. But network package is in big endianness and PC tries to read fields as little endianness. As result, my token field is equal to 0x3412 (and not to 0x1234).

How could I avoid this issue with separate endiannes?

1 Answers
Related