网上有一篇博文分析的非常详细,这里列出参考地址:http://blog.youkuaiyun.com/ce123_zhouwei/article/details/6971544
这里自己列出一些觉得重要的地方,供后续参考。
一、大小端定义
Big-Endian和Little-Endian的定义如下:
1) Little-Endian就是低位字节排放在内存的低地址端,高位字节排放在内存的高地址端。
2) Big-Endian就是高位字节排放在内存的低地址端,低位字节排放在内存的高地址端。
举一个例子,比如数字0x12 34 56 78在内存中的表示形式为:
1)大端模式:
低地址 -----------------> 高地址0x12 | 0x34 | 0x56 | 0x78
2)小端模式:
低地址 ------------------> 高地址0x78 | 0x56 | 0x34 | 0x12
可见,大端模式和字符串的存储模式类似。
二、如何判定大小端1、指针强转方式
#include <stdio.h>
bool IsBigEndian()
{
int a = 0x1234;
char b = *(char *)&a; //通过将int强制类型转换成char单字节,通过判断起始存储位置。即等于 取b等于a的低地址部分
if( b == 0x12)
{
return true;
}
return false;
}
int main()
{
bool judge = IsBigEndian();
printf("endian mode is %d \n", judge);
return 0;
}
2、union方式
#include <stdio.h>
bool IsBigEndian()
{
union NUM
{
int a;
char b;
}num;
num.a = 0x1234;
if( num.b == 0x12 )
{
return true;
}
return false;
}
int main()
{
bool judge = IsBigEndian();
printf("endian mode is %d \n", judge);
return 0;
}
三、常见字节序
一般操作系统是小端,通讯协议时大端。
CPU字节序。。。
文件字节序。。。
JAVA和网络通信协议使用 Big-Endian编码