c语言---位域

来源:互联网 发布:吉首大学教务网络系统 编辑:程序博客网 时间:2024/06/06 18:14
所谓”位域“是把一个字节中的二进位划分为几 个不同的区域, 并说明每个区域的位数。
每个域有一个域名,允许在程序中按域名进行操作。  
它实际上是C语言提供的一种数据结构。
使用位域的好处是:  
1.有些信息在存储时,并不需要占用一个完整的字节,而只需占几个或一个二进制位。
例如在存放一个开关量时,只有0和1 两种状态, 用一位二进位即可。这样节省存储空间,而且处理简便。
这样就可以把几个不同的对象用一个字节的二进制位域来表示。
2.可以很方便的利用位域把一个变量给按位分解


void test()
{
  union ut
{
  struct
  {
    unsigned char x1:2;
    unsigned char x2:2;
    unsigned char x3:2;
    unsigned char x4:2;
  }tt;
  unsigned char s;
}tmp;

  tmp.s = 174;
  printf("tmp.s is %d \n",tmp.s);
  printf("tmp.s is %08x \n",tmp.s);
  printf("tmp.tt.x1 is %d \n",tmp.tt.x1);
  printf("tmp.tt.x2 is %d \n",tmp.tt.x2);
  printf("tmp.tt.x3 is %d \n",tmp.tt.x3);
  printf("tmp.tt.x4 is %d \n",tmp.tt.x4);
}

//结果
tmp.s is 174
tmp.s is 000000ae
tmp.tt.x1 is 2
tmp.tt.x2 is 3
tmp.tt.x3 is 2
tmp.tt.x4 is 2



void test()
{
  struct t1
  {
    char a:2;
    char b:7;
    char c:4;
  };  
    printf("sizeof(struct t1) =%d\n",sizeof(struct t1));
}

sizeof(struct t1) =3
//如果相邻的位域字段的类型不同,在不同的位域类型间,
//按通用的对齐规则进行不同数据类型间的对齐
//(注意,struct的长度是其内部最宽类型的整数倍)
//同时在相同位域类型的字段间按以上两条规则对齐。

void test()
{
  struct t1
  {
    char a:2;
    char b:1;
    char c:4;
  };  

  printf("sizeof(struct t1) =%d\n",sizeof(struct t1));
}

sizeof(struct t1) =1
//如果相邻位域字段的位域类型相同,各个位域字段只占定义时的bit长度。

void test()
{
  struct t1
  {
    char a:1;
    char b:2;
    long d;
  }TT;

  printf("sizeof(struct t1) =%d\n",sizeof(struct t1));
  printf("sizeof(TT) =%d\n",sizeof(TT));
}
//sizeof(struct t1) =8
//sizeof(TT) =8