判斷處理器是Big_endian的還是Little——endian的

原文地址:http://blog.chinaunix.net/uid-25132162-id-1641532.html

首先說明一下Little_endian和Big_endian是怎麼回事,
Little_endian模式的CPU對操作數的存放方式是從低字節到高字節,而Big_endian模式則是從高字節到低字節,比如32位的數0x12345678在兩種模式下的存放如下:
Little_endian:
內存地址       存放內容
0x1000          0x78
0x1001          0x56
0x1002          0x34
0x1003          0x12
 
Big_endian:
內存地址        存放內容
0x1000          0x12
0x1001          0x34
0x1002          0x56
0x1003          0x78
 
而聯合體的存放順序是所有成員都從地址值開始存放,於是可以通過聯合體來判斷。
  1. #include <iostream>
  2. using namespace std;

  3. int CheckCPU()
  4. {
  5.     union
  6.     {
  7.         int a;
  8.         char b;
  9.     }c;
  10.     c.= 1;
  11.     return (c.== 1);
  12. }

  13. int main()
  14. {    
  15.     if (CheckCPU())
  16.     {
  17.         cout<<"Little_endian"<<endl;
  18.     }
  19.     else
  20.     {
  21.         cout<<"Big_endian"<<endl;
  22.     }

  23.     return 0;
  24. }

分析:

在聯合體中定義了兩個成員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.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章