大端字节序和小端字节序
- 小端字节序:低字节存放在低地址,高字节存放在高地址。
- 大端字节序:低字节存放在高地址,高字节存放在低地址。
例:
检查字节序的例子
可以使用联合体来判断系统使用的是什么字节序
#include <stdio.h>
#include <stdlib.h>
union test
{
unsigned short val;
unsigned char byte[2];
};
int main()
{
test typeorder;
typeorder.val = 0xabcd;
printf("byte[0]:0x%x \nbyte[1]:0x%x\n",typeorder.byte[0],typeorder.byte[1]);//
// byte[0]:0xcd 小字节序
// byte[1]:0xab
return 0;
}
运行结果:
可以看出在linux下使用的是小字节序。
字节序转换函数
为了程序设计的方便,让用户的程序与平台无关,linux系统提供了如下函数进行字节序的转换:
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);//主机字节序到网络字节序长整型转换
uint16_t htons(uint16_t hostshort);//主机字节序到网络字节序短整型转换
uint32_t ntohl(uint32_t netlong);//网络字节序到主机字节序长整型转换
uint16_t ntohs(uint16_t netshort);//网络字节序到主机字节序短整型转换
- 进行网络字节序转换时,只要转换一次就可以了,不要进行多次的转换。