c代码小端(大端)字节序的判断方式
1 inline tBool is_little_endian() 2 { 3 unsigned int i = 1; 4 return *(char *)&i; 5 } 6 7 // network order to be big endian 8 inline uint32_t htonl(uint32_t host32) 9 { 10 if (!is_little_endian()) 11 return host32; 12 return ((host32 & 0x000000ff) << 24) 13 | ((host32 & 0x0000ff00) << 8) 14 | ((host32 & 0x00ff0000) >> 8) 15 | ((host32 & 0xff000000) >> 24); 16 } 17 18 inline uint16_t htons(uint16_t host16) 19 { 20 if (!is_little_endian()) 21 return host16; 22 return ((host16 & 0xff) << 8) | ((host16 & 0xff00) >> 8); 23 } 24 25 inline uint32_t ntohl(uint32_t net32) 26 { 27 return htonl(net32); 28 } 29 30 inline uint16_t ntohs(uint16_t net16) 31 { 32 return htons(net16); 33 }