小端序:将低序字节存储在起始地址(intel 处理器采用小端序)。
大端序:将高序字节存储在起始地址。
确定主机字节序的程序:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc,char **argv)
{
union
{
short s;
char c[sizeof(short)];
}un;
un.s=0x0102;
if (sizeof(short)==2)
{
if (un.c[0]==1 && un.c[1]==2) printf("大端序\n");
else if (un.c[0]==2 && un.c[1]==1) printf("小端序\n");
else printf("未知\n");
}
else printf("sizeof(short)= %d\n",sizeof(short));
exit(0);
}
程序运行结果:
字节序转换的四个函数:
#include<nitinet/in.h>
uint16_t htons(uint16_t host16bitvalue);
uint32_t htonl(uint32_t host32bitvalue);
返回值:网络字节序的值
uint16_t ntohs(uint16_t net16bitvalue);
uint32_t ntohl(uint32_t net32bitvalue);
返回值:主机字节序的值