编程区分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
*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章