Little endian 和Big endian 是CPU 存放数据的两种不同顺序。对于整型、长整型等数据类型,Big endian 认为第一个字节是最高位字节(按照从低地址到高地址的顺序存放数据的高位字节到低位字节);而Little endian 则相反,它认为第一个字节是最低位字节(按照从低地址到高地址的顺序存放数据的低位字节到高位字节).
一般来说,x86 系列CPU 都是little-endian 的字节序,PowerPC 通常是Big endian,还有的CPU 能通过跳线来设置CPU 工作于Little endian 还是Big endian 模式.
通过将一个字节(CHAR/BYTE 类型)的数据和一个整型数据存放于同样的内存开始地址,然后读取整型数据,分析CHAR/BYTE 数据在整型数据的高位还是低位来判断CPU 工作于Little endian 还是Big endian 模式.
代码如下:
- #include <iostream>
- using namespace std;
- typedef unsigned char BYTE;
- int main()
- {
- unsigned int num = 0;
- unsigned int* p = #
- *(BYTE *)p = 0xff;
- if(num == 0xff)
- cout<<"The endian of cpu is little"<<endl;
- else //num == 0xff000000
- cout<<"The endian of cpu is big"<<endl;
- return 0;
- }
union 的成员本身就被存放在相同的内存空间(共享内存),因此,我们可以将一个CHAR/BYTE 数据和一个整型数据同时作为一个union 的成员.
代码如下:
#include <iostream>
using namespace std;
typedef unsigned char BYTE;
int main()
{
union
{
int a;
char b;
} un;
un.a = 1;
if(un.b == 1)
cout<<"The endian of cpu is little"<<endl;
else
cout<<"The endian of cpu is big"<<endl;
return 0;
}
转载自:http://blog.youkuaiyun.com/headmaster110/article/details/6582897