原文地址:http://blog.chinaunix.net/uid-25132162-id-1641532.html
-
#include <iostream>
-
using namespace std;
-
-
int CheckCPU()
-
{
-
union
-
{
-
int a;
-
char b;
-
}c;
-
c.a = 1;
-
return (c.b == 1);
-
}
-
-
int main()
-
{
-
if (CheckCPU())
-
{
-
cout<<"Little_endian"<<endl;
-
}
-
else
-
{
-
cout<<"Big_endian"<<endl;
-
}
-
-
return 0;
- }
分析:
在聯合體中定義了兩個成員int和char,而聯合體的大小=sizeof(int)=4,於是在內存中佔四個字節的大小,假設佔用的內存地址爲:0x1000——0x1003,當給a賦值爲1時,此時將根據是Little_endian還是Big_endian來決定1存放的內存地址
如果是Little_endian,則:
內存地址 存放內容
0x1000 0x01
0x1001 0x00
0x1002 0x00
0x1003 0x00
又因爲聯合體的成員都從低地址存放,於是當取0x1000裏面的內容作爲b的值,取得的是0x01,即b=1,因此函數返回值爲1.
如果是Big_endian,則:
內存地址 存放內容
0x1000 0x00
0x1001 0x00
0x1002 0x00
0x1003 0x01
於是當取0x1000裏面的內容作爲b的值,取得的是0x00,即b=0,因此函數返回值爲0.