c++节省内存 联合体和位域的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fanhansheng/article/details/81161784

一:union 联合体

首先我们需要知道struct和union的区别,union的成员是共享内存的,其大小由最大的成员变量决定

我们举个栗子:

#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;
};

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));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/fanhansheng/article/details/81161784
今日推荐