C++的共用体使用场景

2022-10-17  本文已影响0人  何亮hook_8285

C++使用union

描述

union是C语言中一种声明共用体的数据类型,使用union声明的共用体只会占用共用体成员的最大长度类型的内存空间。

共用体使用场景

  1. 节省内存空间
  2. 位操作
  3. 字节操作

节省内存空间

struct video_info{
    int alg;
    int time;
};

struct audio_info{
    int sample_rate;
    int chnnel_cnt;
};

struct av_info{
    char name[4];
    int size;
    //共用体中使用结构体,解决内存占用问题
    union{
        struct video_info vinfo;
        struct audio_info ainfo;
    };
};

位操作

union Byte{
    char a;
    //结构体的位域
    struct{
        unsigned char b1:1;
        unsigned char b2:1;
        unsigned char b3:1;
        unsigned char b4:1;
        unsigned char b5:1;
        unsigned char b6:1;
        unsigned char b7:1;
        unsigned char b8:1;
    }Bit;
};

int main() {
    Byte byte1;
    byte1.a=190;
    printf("%d %d %d %d %d %d %d %d",byte1.Bit.b8,byte1.Bit.b7,byte1.Bit.b6,byte1.Bit.b5,byte1.Bit.b4,byte1.Bit.b3,byte1.Bit.b2,byte1.Bit.b1);
    return 0;
}

字节操作

union IntToByte{
    unsigned int a;
    unsigned char byte[4];
};

int main() {

    IntToByte ito;
    ito.a=1200;
    for(int i=0;i<4;i++)
    {
        printf("%d ",ito.byte[i]);
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读