位域/位字段/字段————特殊的结构体

来源:互联网 发布:谢晋影视艺术学院 知乎 编辑:程序博客网 时间:2024/06/05 08:37

      在存储空间很宝贵的情况下,有时候有的数据会用不到其类型大小所规定的空间,如int/short/int 2, 又如一些开关变量0和1只需用到1个位就足够了,像这些变量若是用足够的类型大小空间来存储的话,真的是很浪费。所以我们常常将几个数据项打包在一个内存字中——位域结构体。

        所谓”位域“是把一个字节中的二进位划分为几 个不同的区域, 并说明每个区域的位数。每个域有一个域名,允许在程序中按域名进行操作。   

       它实际上是C语言提供的一种数据结构。
位域的定义和位域变量的说明位域定义与结构定义相仿,其形式为: 
struct 位域结构名 

类型说明符 位域名1:位域长度;

类型说明符 位域名2:位域长度;

类型说明符 位域名3:位域长度;

};

位域的有些规则——参见标准C程序设计P311

位域的使用:——如与联合体的使用,可以用来获得一个变量的二进制位的内容,

union wy{     struct     {          unsigned char x1:2;          unsigned char x2:2;          unsigned char x3:2;          unsigned char x4:2;     }cn;     unsigned char s;} tmp;

程序如下:

//方法一:用字节访问内存的方法,但最小只能以字节为内存单位union byte{struct      //因为只是要定义一个位域结构体变量,而类型名不需要知道,所以可以可以不取类型名{ char x1:8;  //可以不加unsigned ,不受影响的! char x2:8; char x3:8; char x4:8;}tb;unsigned int a;}tmp;#include<stdio.h> int main()       {unsigned int a = 16777230;  //十六进制表示为: 0x1006printf("%#x  %#x  %#x  %#x\n",((char *)&a)[0],((char *)&a)[1],((char *)&a)[2],((char *)&a)[3]);//从低字节到高字节printf("%p  %p  %p  %p\n",(char *)&a,(char *)&a+1,(char *)&a+2,(char *)&a+3); //显示低字节到高字节的地址tmp.a = 16777230;printf("x1=%d \nx2=%d \nx3=%d \nx4=%d\n",tmp.tb.x1,tmp.tb.x2,tmp.tb.x3,tmp.tb.x4);return 0;       }/*0x6  0  0  0    //显示低字节到高字节的存储的数据0xbfcb382c  0xbfcb382d  0xbfcb382e  0xbfcb382f   //显示低字节到高字节的地址----低地址到高地址----"小端存储"x1=6x2=0 x3=0 x4=0//x1 x2 x3 x4 显示从低字节到高字节的内容*/=============================================================================================================================
//方法二:将位域与联合体合用,最小可以以1 个二进制位为内存单位#if 0#include<stdio.h>union bit{     struct     {          unsigned char x1:2;  //也可以去掉unsigned ,不受影响的!          unsigned char x3:2;             unsigned char x2:2;          unsigned char x4:2;     }cn;     unsigned char s;} tmp;int main(){//位域+联合体的方法1:     tmp.s = 173;                           //二进制形式是10101110     printf("tmp.s is %d\n",tmp.s);     printf("x1 is %d\n",tmp.cn.x1);     printf("x2 is %d\n",tmp.cn.x2);     printf("x3 is %d\n",tmp.cn.x3);     printf("x4 is %d\n",tmp.cn.x4); //位操作符的方法2:     char t = tmp.s;     int i = 8;     while(i--){printf("%d",t>0? 0:1);t<<=1;}     printf("\n");     return 0;}/*输出结果:tmp.s is 173x1 is 1 x2 is 3x3 is 2x4 is 210101101//x4 x3 x2 x1 即是: 10101110*/


0 0