曲径通幽论坛

标题: C 中位域的定义 [打印本页]

作者: beyes    时间: 2011-3-2 12:46
标题: C 中位域的定义
在 C 中,还提供了一种特殊的结构体类型,称之为位域 (bit field)。通俗的讲,就是将一个整数分割为各个位域。其定义形式如:
struct bitdef {
         unsigned int a:1;
         unsigned int b:3;
         unsigned int c:4;
};
注意,上面的定义结构,并不是说有 3 个名称分别为 a, b, c 的 unsigned int 型的整数。a, b, c 分别是一个整数中的不同位域。比如 a 的位域在第 0 位;b 的位域占据了 1-3 位;c 的位域占据了 4-7 位。

所以根据上面的定义,sizeof() 并不适合用在位域上;而且位域自身是没有地址的,也就是说不能有 &a , &b 这样的形式存在。

下面通过代码来进一步说明这个问题。

代码一:
#include <stdio.h>

struct bitdef {
         unsigned int a:1;
         unsigned int b:3;
         unsigned int c:4;
};

int main(void)
{
         struct bitdef test = {0};
         struct bitdef *p = &test;

         printf ("bitdef size: %d\n", sizeof(test));

         return (0);
}
运行输出:
beyes@linux-kd1q:~/C/base/bitdef> ./bit
bitdef size: 4
由上面可见,整个结构体的大小为一个 unsigned int 整型大小,即 4 个字节。当然,如果你定义的位域宽度大于4个字节,那整个结构体的大小也会随之扩大,如讲上面的结构体定义为:
struct bitdef {
         unsigned int a:1;
         unsigned int b:3;
         unsigned int c:4;
         unsigned int d:25;
};
那么整个结构体的大小就为 8 字节。

下面程序简单的示例如何使用位域
#include <stdio.h>

struct bitdef {
         unsigned int a:1;
         unsigned int b:3;
         unsigned int c:4;
};

int main(void)
{
         struct bitdef test = {0};
         struct bitdef *p = &test;

         printf ("bitdef size: %d\n", sizeof(test));

         test.a = 1;
         printf ("0x%x\n", *((unsigned char *)p));

         test.b = 7;
         printf ("0x%x\n", *((unsigned char *)p));

         test.c = 15;
         printf ("0x%x\n", *((unsigned char *)p));

         return (0);
}
运行输出:
beyes@linux-kd1q:~/C/base/bitdef> ./bit
bitdef size: 4
0x1
0xf
0xff





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2