1. 定义
1.1 大端字节序
大端字节序是指一个整数的高位字节(23-31 bit)存储在内存的低地址处, 低字节(0-7 bit)存储在内存的高地址处。
1.2 小端字节序
小端字节序则是指整数的高位字节存储在内存的高地址处, 而低位字节则存储在内存的低地址处。
2. 判断机器字节序
int main(){
union{
short value;
char union_bytes[sizeof(short)];
}test;
test.value = 0x0102;
if((test.union_bytes[0]==1)&&(test.union_bytes[1]==2)){
std::cout << "big endian" << std::endl;
}else if((test.union_bytes[0]==2)&&(test.union_bytes[1]==1)){
std::cout << "small endian" << std::endl;
}else{
std::cout << "unknow..." << std::endl;
}
return 0;
}
3. 转换
Linux提供了如下4个函数来完成主机字节序和网络字节序之间的转换
#include <netinet/in.h>
unsigned long int htonl(unsigned long int hostlong);
unsigned short int htons(unsigned short int hostshort)
unsigned long int ntohl(unsigned long int netlong);
unsigned short int ntohs(unsigned short int netshort)