您的位置:首页 > 理论基础 > 数据结构算法

【转】C的另一重要数据结构bit-fields

2010-05-23 01:28 162 查看
今天看K&R的书的时候顺便温习了C的另一重要数据结构bit-fields,我想bit-fields在编写底层驱动

驱动程序的时候应该比较好用,它可以绕开"&"和"|"进行位操作,而且更加节约内存空间。废话不多说

了,还是先来看看它的真面目吧:

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位

二进位。

总结:

这些差别可能是因为编译器对这种数据结构的实现的差异造成的,国内教科书直接将field的存储单元

定义为一个字节了,这个以后还需要继续研究。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: