最近工作中,有两次遇到大小端问题,所以花时间写这篇日志,总结一下。
int checkCPUendian()//返回1,为小端;反之,为大端; { union { unsigned int a; unsigned char b; }c; c.a = 1; return 1 == c.b; }
(2) 大端模式处理器的字节序到网络字节序不需要转换,此时ntohs(n)=n,ntohl =n;而小端模式处理器的字节序到网络字节必须要进行转换(同理,有时候需要将大端字节顺序转换成小端字节顺序,也用这个函数,因为这个函数本来就是用来颠倒字节顺序的),转换如下:
#if defined(BIG_ENDIAN) && !defined(LITTLE_ENDIAN) #define htons(A) (A) #define htonl(A) (A) #define ntohs(A) (A) #define ntohl(A) (A) #elif defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN) #define htons(A) ((((uint16_t)(A) & 0xff00) >> 8 ) | \\ (((uint16_t)(A) & 0x00ff) << 8 )) #define htonl(A) ((((uint32_t)(A) & 0xff000000) >> 24) | \\ (((uint32_t)(A) & 0x00ff0000) >> 8 ) | \\ (((uint32_t)(A) & 0x0000ff00) << 8 ) | \\ (((uint32_t)(A) & 0x000000ff) << 24)) #define ntohs htons #define ntohl htohl #else #error Either BIG_ENDIAN or LITTLE_ENDIAN must be #defined, but not both. #endif