字节序
2023年6月13日更新
注意:
无论是大端字节序还是小端字节序,内存中的字节顺序是一样的。区别在于当我们把这些字节解释为更大的数据类型(如short,int等)时,不同的字节序规则会影响我们如何从内存中的字节构造出这些更大的数据类型。
数据在内存中存储的方式
-
大端序(网络字节序):高位的数据存放在低地址位(ARM,网络设备等)
-
小端序(本机字节序):高位的数据存放在高地址位(X86等)
这就是为什么在网络的例子中在设置sockaddr_in的端口号的时候要使用转换函数把大端转换为小段
字节序转换
-
本机字节序–>网络字节序 htons( )
-
网络字节序–>本机字节序 ntohs( )
函数
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
//DESCRIPTION:
The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.
The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.
The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.
The ntohs() function converts the unsigned short integer netshort from network byte or‐der to host byte order.
On the i386 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first.