虽说现在大部分x86服务器都是小端字节序,但在嵌入式设备上,由于芯片种类繁多,大小端序均有。需考虑程序的可移植性。
一.字节序判断
int bigendian() { union { short value; char ubytes[ sizeof(short) ]; }test; test.value = 0x0102; if( (test.ubytes[0] == 1) && (test.ubytes[1] == 2) ) { return 1; } return 0; }
上述代码用union结构巧妙实现对字节序的判断
二.字节序转换函数
ntohs()将网络字节序转化为主机字节序
htons()将主机字节序转化为网络字节序
ntohl(),htonl()处理int类型
# 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
ntohs与htons实现一致,都是调用__bswap_32 (x)。由于大端服务器上主机序与网络序一致,不需要转换,所以实现直接返回原值x。
所以只需要考虑小端服务器上的转换,大端服务器无须理会ntohs()调用,代码本身就跨平台。