问题:编写一个函数。若处理器使用Big_endian模式存储数据,则返回0;若使用Little_endian模式存储数据,则返回1。
答案:
int checkCPU()
{
union w
{
int a;
char b;
}c;
c.a=1;
return(c.b=1);//Little_endian模式返回1
}
分析:
(1)采用Little_endian模式的CPU对操作数的存储方式是从低字节到高字节;
而Big_endian模式的CPU对操作数的储存方式是从高字节到低字节
(2)32位宽的数0x12345678
Little_endian模式CPU(Intelx86)内存中的存放方式为(假设从0x40000开始)
0x4000 0x78
0x4001 0x56
0x4002 0x34
0x4003 0x12
而Big_endian模式CPU内存中的存放方式为
0x4000 0x12
0x4001 0x34
0x4002 0x56
0x4003 0x78