How can I convert little endian to big endian usin

2019-08-31 12:36发布

问题:

I have struct with the following elements. Plus the structure is complety padded.

typedef struct {
    uint16_t a;
    uint16_t b;
    uint8_t c;
    uint8_t d;
    uint8_t e[6];
} ad;

This structure is a little endian. I mean when I print this structure on my big endian machine I get the following

if c=1 , d=2, e[0] =3, e[1]=4. I get

c=4, d=3, e[0] = 2 and e[1]=1.

a and b are swapped. further, e[1] is swapped with c and e[0] is swapped with d.

I am using htonl function like the following. but, it is not working, can anyone suggest me a good answer.

回答1:

Endian-ness only applies to individual fields, not the order of struct fields. Of the fields you list, only the multi-byte integer fields defined as uint16_t will are governed by endian-ness the uint8_t are single byte, so there is no ordering issue to consider. The array of single byte values will also maintain the same length regardless of the endian-ness.

To convert the uint16_t, you will want to use the htons() function instead of htonl(). The htonl() function expects a long which will typically be at least 4 bytes.

uint16_t netShort = htons(uint16_t hostShort);

Or for your example struct:

struct.a = htons(struct.a);
struct.b = htons(struct.b); 


回答2:

For the first two elements a and b, they are uint16_t, so you should use htons/ntohs to convert them. The rest three elements c, d and e, they are uint8_t, you don't need to convert them.

By the way, I don't know if or not you use ntohl on the variable ad (struct), just clarify to you that you should convert each element of a struct one by one rather than convert the entire struct variable with ntohl/ntohs/htonl/htons.