首页 > 其他 > 详细

union中内嵌struct

时间:2021-02-20 17:58:33      阅读:38      评论:0      收藏:0      [点我收藏+]

使用union中内嵌struct这种方法,可以打包和解析数据

#include<iostream>
using namespace std;
//用来解析
// bit-field used to unpack the st_mode in field in a _stat structure
struct modes
{
    unsigned others : 3;    // permissions for everyone else
    unsigned group  : 3;    // group permissions
    unsigned user   : 3;    // file owner permissions
    unsigned type   : 7;    // other file data - directory or regular file?
};

//在16bit和mode 位间映射
union map    // used to map between a 16-bit int and a mode bit field.
{
    unsigned short statmode;    // data input as 16-bit int  已16-bit输入
    modes convert;            // data output as modes bit field. 位域输出
};

int main()
{
    map    mapper;
    //存储16-bit整数到mapper的statmode域
//store a 16-bit integer into the mapper‘s statmode field
    mapper.statmode =0x88;

//read the unpacked information out of the mapper‘s convert field, which further divides the data into bit-fields
//从mapper转换域读解析信息,然后分数据到位域
    cout << mapper.convert.user << endl;
    cout << mapper.convert.group << endl;
    cout << mapper.convert.others << endl;

}

技术分享图片

技术分享图片

技术分享图片技术分享图片技术分享图片

union中内嵌struct

原文:https://www.cnblogs.com/beepeg/p/14421956.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!