• 结构体成员有冒号 位域 位段


    参考的文档是:https://www.cnblogs.com/maowang1991/p/3656072.html

    如下面的结构:

    struct
    {
    unsigned char x1:1;
    unsigned char x2:1;
    unsigned char x3:1;
    unsigned char x4:1;
    unsigned char x5:1;
    unsigned char x6:1;
    unsigned char x7:1;
    unsigned char x8:1;
    }cn;

    类型与结构体,但是他是位域,或者叫做位段操作。

    这里面的成员如x1被定义为:unsigned char x1:1;

    这里后面的冒号 :1代表的是x1占用了一位,而不是unsigned char。

    为什么要用位域操作:

    好处一节省空间,这个似乎没有特别大的作用,因为现在基本上不差这点内存。比如:可以用1位而不是用一个字节表示开关。

    好处二分解变量,这个可以按照位,把变量分开。运算快,比较省事。

    下面实验如果实现把变量按照位进行分解:

    这里需要用到:union,也就是联合,

    联合的好处就是里边的所有变量都用的是一个内存空间。

    测试程序:

    //所用的在线工具:https://www.it1352.com/Onlinetools/details/6 
    
    //gcc 5.4.0
    
    #include "stdio.h"
    
    //下面这里是一个联合wy,
    //里面 cn 变量和 s 变量用的是一个内存
    //也就是改变一个,另一个也会改变
    union wy { struct { unsigned char x1:1; unsigned char x2:1; unsigned char x3:1; unsigned char x4:1; unsigned char x5:1; unsigned char x6:1; unsigned char x7:1; unsigned char x8:1; }cn; unsigned char s; } tmp;

    int main() { tmp.s =0xf0; //二进制形式是1111 0000 给s赋值,就是给cn赋值
    //因为进行了联合。
    printf("tmp.s is %d ",tmp.s); printf("tmp.s is %x ",tmp.s); printf("x1 is %d ",tmp.cn.x1); printf("x2 is %d ",tmp.cn.x2); printf("x3 is %d ",tmp.cn.x3); printf("x4 is %d ",tmp.cn.x4); printf("x5 is %d ",tmp.cn.x5); printf("x6 is %d ",tmp.cn.x6); printf("x7 is %d ",tmp.cn.x7); printf("x8 is %d ",tmp.cn.x8); return 0; }

    输出的结果:

    tmp.s is 240 
    tmp.s is f0   //给s赋值 1111 0000
    x1 is 0       //这里是低位
    x2 is 0
    x3 is 0
    x4 is 0
    x5 is 1
    x6 is 1
    x7 is 1
    x8 is 1      //这里是高位

     因此就会把每一位的数据都展开,从而知道是0还是1.

  • 相关阅读:
    团队冲刺第一天
    第八周进度报告
    团队会议01
    《梦断代码》阅读笔记(三)
    《梦断代码》阅读笔记(二)
    《梦断代码》阅读笔记(一)
    SCRUM第六天
    SCRUM第五天
    大白话strom——问题收集(持续更新ing)
    maven环境快速搭建(转)
  • 原文地址:https://www.cnblogs.com/chulin/p/12781597.html
Copyright © 2020-2023  润新知