位域 bit-fields C的重要数据结构

详见K&R书上的6.9 section

bit-field来源:
bit-field是为了节约存储空间而创造的一种数据结构(to pack several objects into a single
machine word)
 
bit-field用途:
Externally-imposed data formats,such interfaces to hardware devices,also often
require the ability to get a pieces of a word
 
定义方法:
struct (tag) {
bit-field list ~~~
} bit-field variable list;
 
由定义方法可见,bit-field也是以structure的形式组织起来的数据结构,只不过是以二进制进行分发
的而已。其中bit-field list表示方法: type fieldnamme:width; width:field的宽度,以bit
表示,还是举个例子来看吧:
 
struct bf{
unsigned int is_keyword:1;
unsigned int is_extern:1;
unsigned int is static:1;
}flags;
 
定义了一个bit-field变量flags,它包括3个1-bit的field,访问bit-field其实和访问一般数据结
构的成员一样,例如:
flags.is_static=0;
 
在定义bit-field的时候,有以下几点要注意(K&R版本的观点)
1、Almost everything about fields is implemention-dependent ! Whether a field may
   overlap a word boundary is implemention-defined.
2、Fields can only be declared as intS,for protability,specify signed or unsigned
   explicitly.
3、unnamed field can be used for padding(没有名字的field可以用来作为填充或者调整用)
   例如:
   struct bf{
   unsigned int a:2;
   unsigned int  :4; /*该4位不能用*/
   unsigned int b:2;
   };
 
 4、Special width 0 may be used to force alignment at the next word boundary.
   (如果width=0的话,那么下一个field就被强制存放在下一个内存单元里面了),例如:
  
   struct bf{
   unsigned int a:2;
   unsigned int  :0; /*空的field*/
   unsigned int b:2; /*从下一个单元开始存放*/
   };
 
 5、Bit-field are not arrays and they do not have addresses , so the operator &
    can not be applied on them.
 
 某些国内的教科书上与K&R对field定义规则的描述还是有些不同,比如谭浩强版本写道:
 
 1) 一个位域必须存储在同一个字节中,不能跨两个字节。如一个字节所剩空间不够存放另一位域时,
    应从下一单元起存放该位域。
 2) 由于位域不允许跨两个字节,因此位域的长度不能大于一个字节的长度,也就是说不能超过8位
    二进位。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值