Union and entity without htonl / ntohl

I want to parse the header of my TCP packet that I am receiving.

Let's 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 efficiently on Windows platform. I made the following 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;

      

Then I tried to copy the package above to my array bytes

. But the network packet is in a big encyclopedia, and the PC tries to read the fields as minimal. As a result, my field token

is equal 0x3412

(not 0x1234).

How could I avoid this problem with individual endiannes?

+3


source to share


1 answer


Boost provides a library dedicated to endianess:

http://www.boost.org/doc/libs/1_61_0/libs/endian/doc/index.html

For example:

boost::endian::big_to_native_inplace(bar.field.command);

      



or AndyG:

std::cout << boost::endian::endian_reverse(bar.field.token) << std::endl;

      

Note. This library has three ways to deal with content, you need to spend time on what is right for your case.

+4


source







All Articles