一:union 联合体
首先我们需要知道struct和union的区别:struct的大小遵循字节对齐。union的成员是共享内存的,其大小由最大的成员变量决定。
32位和64位的区别是 long的字节数和指针所占的字节数。
这里我们只讲位域和联合体的小端模式下内存的字节占用情况。
我们举个栗子:
#include <iostream>
#include <cstdio>
using namespace std;
union test1{
int a;
char b;
short int c;
};
struct test2{
int a;
char b;
short int c;
};
int main()
{
printf("联合体的大小 %d 结构体的大小 %d\n", sizeof(test1), sizeof(test2));
return 0;
}
输出是 4 和 8. union的大小取决于最大的int占用字节 4个 而struct 根据字节对齐 int 占4个 char和short int 一共占4个
位域是根据给结构体或联合体的成员分配位数。我们知道char 占一个字节 需要用8位去表示。范围是 -128-127 最高位是符号位。
如果我们给char的位数只分配两个。那么它的范围也就变成了-2 - 1 如果超出位数 就会有个取余处理。
我们看一下栗子:
#include <iostream>
#include <cstdio>
using namespace std;
union test1{
struct {
unsigned int a:4;
int b:4;
unsigned int c:4;
}dk;
int k;
};
union x{
int a;
char b;
};
int main()
{
test1 test;
test.k=0;
test.dk.a=15;//1111
test.dk.b=100;//0100
test.dk.c=-10;//0110
printf("%d\n", test.k);//011001001111 1615 低地址存放低字节(小端模式)
printf("%d\n", sizeof(test1));
x u;
u.a=0x12345678;
printf("%d\n", u.b); //每个16进制占4位,内存分配给union的一共是是8字节32位,根据小端模式,u.b=0x78再转换成十进制就是120.
return 0;
}