編寫一段代碼判斷系統中的CPU是小端還是大端模式?
方法1:將一個字節的數據和一個整型數據存放於同樣的內存的開始地址
通過讀取整數數據,分析字節在整型數據的高位還是地位來判斷CPU工作於小端還是大端
大端認爲第一個字節是最高位字節(按照從低地址到高地址的順序存放數據的高位字節到低位字節)
小端正相反,認爲第一個字節是最低位字節(低地址到高地址存放數據的低位字節到高位字節)
一般來說X86是小端字節序(常見),PowerPC是大端
#include <stdio.h>
typedef unsigned char BYTE;
int main()
{
unsigned int num, *p;
p = #
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
*/