【轉】判斷處理器是Big_endian的還是Little_endian的


首先說明一下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

 

而聯合體的存放順序是所有成員都從地址值開始存放,於是可以通過聯合體來判斷。

#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來決定存放的內存地址。

如果是Little_endian,則

內存地址      存放內容

0x1000        0x01

0x1001                          0x00

0x1002        0x00

0x1003                          0x00

又因為聯合體的成員都從低地址存放,於是當取0x1000里面的內容作為b的值,取得的是0x01,即b=1,函數返回值為1,說明處理器是Little_endian。否則,則是Big_endian。

 

轉自:http://blog.chinaunix.net/uid-25132162-id-1641532.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM