美文网首页
C++的共用体使用场景

C++的共用体使用场景

作者: 何亮hook_8285 | 来源:发表于2022-10-17 23:42 被阅读0次

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

    相关文章

      网友评论

          本文标题:C++的共用体使用场景

          本文链接:https://www.haomeiwen.com/subject/aqhjzrtx.html