为什么8位字段具有字节顺序? [英] Why does an 8-bit field have endianness?
问题描述
请参见/netinet/tcp.h中的TCP标头的定义:
See the definition of TCP header in /netinet/tcp.h:
struct tcphdr
{
u_int16_t th_sport; /* source port */
u_int16_t th_dport; /* destination port */
tcp_seq th_seq; /* sequence number */
tcp_seq th_ack; /* acknowledgement number */
# if __BYTE_ORDER == __LITTLE_ENDIAN
u_int8_t th_x2:4; /* (unused) */
u_int8_t th_off:4; /* data offset */
# endif
# if __BYTE_ORDER == __BIG_ENDIAN
u_int8_t th_off:4; /* data offset */
u_int8_t th_x2:4; /* (unused) */
# endif
u_int8_t th_flags;
# define TH_FIN 0x01
# define TH_SYN 0x02
# define TH_RST 0x04
# define TH_PUSH 0x08
# define TH_ACK 0x10
# define TH_URG 0x20
u_int16_t th_win; /* window */
u_int16_t th_sum; /* checksum */
u_int16_t th_urp; /* urgent pointer */
};
为什么8位字段的字节序顺序不同?我认为只有16位和32位字段与字节顺序有关,并且可以分别在ntohs和ntohl的字节序之间进行转换。处理8位内容的功能是什么?如果没有,则似乎在小字节序的计算机上使用此标头的TCP不能与在大字节序的计算机上的TCP一起使用。
Why does the 8-bit field have a different order in endianness? I thought only 16-bit and 32-bit fields mattered with byte order, and you could convert between endians with ntohs and ntohl, respectively. What would the function be for handling 8-bit things? If there is none, it seems that a TCP using this header on a little endian machine would not work with a TCP on a big endian machine.
推荐答案
有两种顺序。一种是字节顺序,一种是位域顺序。
C语言中没有关于位域顺序的标准顺序。这取决于编译器。通常,位域的顺序在大小端之间颠倒。
There are two kind of order. One is byte order, one is bitfield order. There is no standard order about the bitfield order in C language. It depends on the compiler. Typically, the order of bitfields are reversed between big and little endian.
这篇关于为什么8位字段具有字节顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!