htons、htonl與字節序大小端
判斷字節序大小端code
#include <stdio.h> int main() { if (htons(1) == 1) printf("big endian\n"); else printf("little endian\n"); return 0; }
int main() { printf("0x%x\n", htons(0x9225)); printf("0x%x\n", htonl(0x9225)); }
上述code輸出數值為:
$ ./a.out
0x2592
0x25920000
方便理解。
除了
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
之外,還有如下用於字節序轉換的函數,需要的時候可以查閱:
#include <endian.h>
uint16_t htobe16(uint16_t host_16bits);
uint16_t htole16(uint16_t host_16bits);
uint16_t be16toh(uint16_t big_endian_16bits);
uint16_t le16toh(uint16_t little_endian_16bits);
uint32_t htobe32(uint32_t host_32bits);
uint32_t htole32(uint32_t host_32bits);
uint32_t be32toh(uint32_t big_endian_32bits);
uint32_t le32toh(uint32_t little_endian_32bits);
uint64_t htobe64(uint64_t host_64bits);
uint64_t htole64(uint64_t host_64bits);
uint64_t be64toh(uint64_t big_endian_64bits);
uint64_t le64toh(uint64_t little_endian_64bits);
htons、htonl與字節序大小端