问题描述
我具有以下元素的结构。
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;
此结构有点小尾数。我的意思是,当我在大字节序机器上打印此结构时,如果c = 1,d = 2,e [0] = 3,e [1],则得到以下结果
This structure is a little endian. I mean when I print this structure on my big endian machine I get the following
] = 4。
我得到
if c=1 , d=2, e[0] =3, e[1]=4.I get
c = 4,d = 3,e [0] = 2和e [1] = 1。
c=4, d=3, e[0] = 2 and e[1]=1.
a和b被交换。
,e [1]与c交换,e [0]与d交换。
a and b are swapped.further, e[1] is swapped with c and e[0] is swapped with d.
我正在使用 htonl
函数如下所示。
I am using htonl
function like the following. but, it is not working, can anyone suggest me a good answer.
推荐答案
Endian-ness仅适用于单个字段,而不适用结构字段的顺序。在您列出的字段中,仅定义为uint16_t的多字节整数字段将由字节顺序控制,而uint8_t是单字节,因此不存在排序问题。无论字节顺序如何,单字节值数组都将保持相同的长度。
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.
要转换uint16_t,您将需要使用htons()函数来代替htonl()。 htonl()函数期望的长度通常至少为4个字节。
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);
或者以您的示例struct:
Or for your example struct:
struct.a = htons(struct.a);
struct.b = htons(struct.b);
这篇关于如何使用htonl将Little Endian转换为Big Endian的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!