本地字节序--> 网络字节序 -->本地字节序
字节序转换函数:
htons和htonl是将本地字节序转换为网络字节序,htons是对16位整数进行转换,htonl是对32位正数进行转换,ntohs和ntohl恰好相反。
判断主机字节序和网络字节序:
#include<arpa/inet.h>
#include<stdio.h>
//judge host endian
void judge_host_endian()
{
short arg = 0x0102;
short* ap = &arg;
char* temp = (char*)ap;
if(*temp==0x01)
{
puts("host:big-endian");
}
else if(*temp==0x02)
{
puts("host:small-endian");
}
}
//judge net endian
void judge_net_endian()
{
uint16_t arg = htons((uint16_t)0x0102);
short* ap = &arg;
char* temp = (char*)ap;
if(*temp==0x01)
{
puts("net:big-endian");
}
else if(*temp==0x02)
{
puts("net:small-endian");
}
}
int main()
{
judge_host_endian();
judge_net_endian();
return 0;
}
所以win7是small-endian,网络字节序是big-endian。