联合体 union,判断系统的大小端存储

时间:2022-09-05 17:03:41
大端模式:高地址存放低字节;小端模式:高地址存放高字节;

例如 int num =0x12345678

内存地址 小端模式存放内容 大端模式存放内容
0x4000 0x78 0x12
0x4001 0x56 0x34
0x4002 0x34 0x56
0x4003 0x12 0x78
#include <stdio.h>


union  num{
	int int_num;
	char char_num_union[2];
	
}num;
int main(int argc,char *argv[])
{
	void *number=0;
	num.char_num_union[0]=11;
	num.char_num_union[1]=1;
	printf("num.int_num:%d\n",num.int_num);
	if(num.int_num == 267){
		printf("小端\n");
	}else if(num.int_num == 2817){
		printf("大端\n");
		
	}
	num.int_num=0x1234;
	printf("num.char_num_union[0] is %d,num.char_num_union[1] is %d\n",num.char_num_union[0],num.char_num_union[1]);
	if(int(num.char_num_union[0]) == 18 && int(num.char_num_union[1]) == 52){
		printf("大端\n");
	}else if(int(num.char_num_union[0]) == 52 && int(num.char_num_union[1]) == 18){
		printf("小端\n");
		
	}
	
}

结果:

联合体 union,判断系统的大小端存储