编写一段代码判断系统中的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
*/