htons()将主机字节顺序转换为网络字节顺序.
网络字节顺序是Big-Endian,主机字节顺序可以是Little-Endian或Big-Endian.
在Little Endian系统上,htons()会将多字节变量的顺序转换为Big-Endian.如果主机字节顺序也是Big-Endian,htons()会做什么?
最佳答案
What will
htons()
do in case if the host byte order is also big endian?
没什么 – 非常字面.首先介绍htons()的目的是让您编写不关心系统字节序的代码.定义函数的头文件是端点发挥作用的唯一位置.
这是one implementation,用括号围绕其参数表达式替换htons:
#if BYTE_ORDER == BIG_ENDIAN
#define HTONS(n) (n)
#define NTOHS(n) (n)
#define HTONL(n) (n)
#define NTOHL(n) (n)
#else
#define HTONS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
#define NTOHS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
#define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
((((unsigned long)(n) & 0xFF00)) << 8) | \
((((unsigned long)(n) & 0xFF0000)) >> 8) | \
((((unsigned long)(n) & 0xFF000000)) >> 24))
#define NTOHL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
((((unsigned long)(n) & 0xFF00)) << 8) | \
((((unsigned long)(n) & 0xFF0000)) >> 8) | \
((((unsigned long)(n) & 0xFF000000)) >> 24))
#endif
#define htons(n) HTONS(n)
#define ntohs(n) NTOHS(n)
#define htonl(n) HTONL(n)
#define ntohl(n) NTOHL(n)