1.大小端
大端字节序:高地址储存在低位
小端字节序:高地址存储在高位
2.判断
#include
int main()
{
int a = 1;
char ch = *(char*)&a;
if(ch)
printf("littlen");
else
printf("bign");
return 0;
}
3.共用体判断
#include
union
{
char ch;
int a;
}un;
int main()
{
un.a = 0x12345678;
if(ui.ch == 0x12)
printf("bign");
else
printf("littlen");
return 0;
}
4.网络字节序
- 网络上传输的数据都是{% label 字节流 blue %},对于一个多字节的数值的传输,先传输那个字节?接受端接收的第一个字节作为高字节还是低字节?
//UDP/TCP/IP协议规定,把接收到的第一个字节作为高字节看待,也就是网络字节序是大端字节序
//字节序转换函数
#include
//主机字节序转化为网络字节序
unit32_t htonl (unit32_t hostlong);
unit16_t htons (unit16_t hostshort);
//网络字节序转化为主机字节序
unit32_t ntohl (unit32_t netlong);
unit16_t ntohs (unit16_t netshort);
#include
#include
int main()
{
unsigned int x = 0x12345678;
unsigned char *p = (unsigned char *)&x;
printf("%0x_%0x_%0x_%0xn",p[0],p[1],p[2],p[3]);
unsigned int y = htonl(x);
p = (unsigned char*)&y;
printf("%0x_%0x_%0x_%0xn",p[0],p[1],p[2],p[3]);
return 0;
}
//output
78_56_34_12
12_34_56_78