因为需要直接处理一个网络字节序的 32 位 int,所以,考虑用自己写的还是系统函数效率更高。然后又了下面的了解。
首先是系统函数 htonl ,我在 kernel 源码 netinet/in.h 找到如下定义:
# if __BYTE_ORDER ==__BIG_ENDIAN/*The host byte order is the same as network byte order,
so these functions are all just identity.*/# define ntohl(x) (x)
# define ntohs(x) (x)
# define htonl(x) (x)
# define htons(x) (x)
#else#if __BYTE_ORDER ==__LITTLE_ENDIAN
# define ntohl(x) __bswap_32 (x)
# define ntohs(x) __bswap_16 (x)
# define htonl(x) __bswap_32 (x)
# define htons(x) __bswap_16 (x)
# endif
# endif#endif
可以看到,如果系统是 BIG_ENDIAN 那么网络字节序和运算字节序是一致的,如果是 LITTLE_ENDIAN 那么需要进行 __bswap_32() 操作。__bswap_32() 在 gcc 中实现,位于bits/byteswap.h(不要直接引用此文件;使用 byteswap.h 中的 bswap32 代替):
/*Swap bytes in 32 bit value.*/
#define __bswap_constant_32(x) \((