htonshtonl与字节序大小端
Posted rivsidn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了htonshtonl与字节序大小端相关的知识,希望对你有一定的参考价值。
判断字节序大小端code
#include <stdio.h> int main() { if (htons(1) == 1) printf("big endian "); else printf("little endian "); return 0; }
int main() { printf("0x%x ", htons(0x9225)); printf("0x%x ", 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);
以上是关于htonshtonl与字节序大小端的主要内容,如果未能解决你的问题,请参考以下文章
百度笔试题简述大小端字节序的概念并写一个小程序检测当前机器的大小端字节序
百度笔试题简述大小端字节序的概念并写一个小程序检测当前机器的大小端字节序
手把手写C++服务器(20):网络字节序与主机字节序大端小端与共用体