大端模式(Big_endian):字数据的
高字节存储在
低地址中,而字数据的
低字节则存放
在
高地址中。
小端模式(Little_endian):字数据的
高字节存储在
高地址中,而字数据的
低字节则存放
在
低地址中。
union型数据所占的空间等于其最大的成员所占的空间。对union型的成员的存取都是
相对于该联合体基地址的偏移量为0处开始,也就是联合体的访问不论对哪个变量的存取都
是从union的首地址位置开始。
一般情况,我们的计算机都是小端模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 1#include<stdio.h>
2#include<string.h>
3#include<stdlib.h>
4typedef struct st_typy
5{
6 int i;
7 int a[0];
8}type_a;
9union
10{
11 int i;
12 char a[2];
13}*p,u;
14
15void main(void)
16{
17 int a[5] = {1,2,3,4,5};
18 int *ptr=(int *)(&a+1);
19 p=&u;
20 p->a[0]=0x39;
21 p->a[1]=0x38;
22
23 printf("p->i=0x%X\n",p->i);
24 printf("%d\n",sizeof(type_a));
25 printf("%d,%d\n",*(&a+1-1),*(ptr-1));
26}
27
1
2 1 假设: printf("p->i=0x%X\n",p->i); 打印的是0x3938说明高字节存在低地址中,那么就是大端模式
2
printf("p->i=0x%X\n",p->i); 打印的是0x3839说明高字节存在高地址中,那么就是小端模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 1#include<stdio.h>
2#include<string.h>
3#include<stdlib.h>
4typedef struct st_typy
5{
6 int i;
7 int a[0];
8}type_a;
9union
10{
11 int i;
12 char a[2];
13}*p,u;
14int checkSystem()
15{
16 union check
17 {
18 int i;
19 char ch;
20 }c;
21 c.i=1;
22 return((c.ch==1)?1:0);
23}
24
25void main(void)
26{
27 int a[5] = {1,2,3,4,5};
28 int *ptr=(int *)(&a+1);
29 int i=1;
30 p=&u;
31 p->a[0]=0x39;
32 p->a[1]=0x38;
33 if(checkSystem)
34 {
35 printf("计算机是小端模式\n");
36 }
37 printf("p->i=0x%X\n",p->i);
38 printf("%d\n",sizeof(type_a));
39 printf("%d,%d\n",*(&a+1-1),*(ptr-1));
40}
41