htons()/ntohs()函数使用?具体请看代码
#include<stdio.h>#include<arpa/inet.h>union{shorts;charc[sizeof(short)];}un,nn;intmai...
#include <stdio.h>
#include <arpa/inet.h>
union {
short s;
char c[sizeof(short)];
}un,nn;
int main()
{
un.s=0x0102;
if(sizeof(short)==2)
{
if(un.c[0]==1&&un.c[1]==2)
printf("1big-endian\n");
else if(un.c[0]==2&&un.c[1]==1)
printf("1littel-endian\n");
}
else
{
printf("sizeof(short)=%d\n",sizeof(short));
}
nn.s=htons(un.s); 注意:用这句和下面注释掉的语句输出结果一样结果一样。为什么?
//nn.s=ntohs(un.s);
if(sizeof(short)==2)
{
if(nn.c[0]==1&&nn.c[1]==2)
printf("2big-endian\n");
else if(nn.c[0]==2&&nn.c[1]==1)
printf("2littel-endian\n");
}
else
{
printf("sizeof(short)=%d\n",sizeof(short));
}
return 0;
} 展开
#include <arpa/inet.h>
union {
short s;
char c[sizeof(short)];
}un,nn;
int main()
{
un.s=0x0102;
if(sizeof(short)==2)
{
if(un.c[0]==1&&un.c[1]==2)
printf("1big-endian\n");
else if(un.c[0]==2&&un.c[1]==1)
printf("1littel-endian\n");
}
else
{
printf("sizeof(short)=%d\n",sizeof(short));
}
nn.s=htons(un.s); 注意:用这句和下面注释掉的语句输出结果一样结果一样。为什么?
//nn.s=ntohs(un.s);
if(sizeof(short)==2)
{
if(nn.c[0]==1&&nn.c[1]==2)
printf("2big-endian\n");
else if(nn.c[0]==2&&nn.c[1]==1)
printf("2littel-endian\n");
}
else
{
printf("sizeof(short)=%d\n",sizeof(short));
}
return 0;
} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询