編程區分CPU大小端


編寫一段代碼判斷系統中的CPU是小端還是大端模式?

方法1:將一個字節的數據和一個整型數據存放於同樣的內存的開始地址

通過讀取整數數據,分析字節在整型數據的高位還是地位來判斷CPU工作於小端還是大端

        大端認爲第一個字節是最高位字節(按照從低地址到高地址的順序存放數據的高位字節到低位字節)
        小端正相反,認爲第一個字節是最低位字節(低地址到高地址存放數據的低位字節到高位字節)

一般來說X86是小端字節序(常見),PowerPC是大端

#include <stdio.h>

typedef unsigned char BYTE;

int main()
{
    unsigned int num, *p;
    p = &num;
    num = 0;

    *(BYTE *)p = 0xff;

    if (num == 0xff) {
        printf("The endian of cpu is little\n");
    } else {
        printf("The endian of cpu is big\n");   //num = 0xff000000
    }

    return 0;
}


/*
The endian of cpu is little
*/
方法2;union成員本身被存在相同的內存空間(共享內存)
#include <stdio.h>

int checkCPU()
{
    union w
    {
         int a;
         char b;
    } c;

    c.a = 1;

    return (c.b == 1);
}

int main()
{
    int is;
    is =checkCPU();

    if (is == 1) {
        printf("The endian of cpu is little\n");
    } else {
        printf("The endian of cpu is big\n");
    }

    return 0;
}

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