如何判断大小端模式?

通过写程序判断 CPU 的大小端模式:

大端模式就是低字节存储在高地址处而高字节存储在低地址处

小段模式就是低字节存储在低地址处而高字节存储在高地址处

根据这个特性,假设我们初始化了一个int变量i为0x12345678,其地址为0x100,根据定义在小端模式下

0x100一个字节内的值为0x78,类推0x101=>0x56,0x102=>0x34,0x103=0x12,根据这个编程如下

 

typedef union {
	int i;
	char c;
}my_union;    //定义联合结构
 
int checkSystem1(void)
{
	my_union u;
	u.i = 1;
	return (u.i == u.c);
}
int checkSystem2(void)
{
	int i = 0x12345678;
	char *c = &i;
	return ((c[0] == 0x78) && (c[1] == 0x56) && (c[2] == 0x34) && (c[3] == 0x12));
}
int main()
{
	if(checkSystem1())
		printf("little endian\n");
	else
		printf("big endian\n");
 
	if(checkSystem2())
		printf("little endian\n");
	else
		printf("big endian\n");
 
	return 0;
}

运行结果:

如何判断大小端模式?

其他请参考文章:https://blog.****.net/dyllove98/article/details/8923298