开发者

Bit field manipulation disadvantages

I was reading this link

http://dec.bournemouth.ac.uk/staff/awatson/micro/articles/9907feat2.htm

I could not understand this following statements from the link, Please help me understand about this.

The programmer just writes some macros that shift or mask the appropriate bits to get what is desired. However, if the data involves longer binary encoded records, the C API runs into a problem. I have, over the years, seen many lengthy, complex binary records described with the short or long integer bit-field definition facilities. C limits these bit fields to subfields of integer-defined variables, which implies two limitations: first of all, that bit fields may be no wider, in bits, than the underlying variable; and secondly, that no bit field should overlap the underlying variable boundaries. Complex records are usually composed of several contiguous long integers populated with bit开发者_运维技巧-subfield definitions.

ANSI-compliant compilers are free to impose these size and alignment restrictions and to specify, in an implementation-dependent but predictable way, how bit fields are packed into the underlying machine word structure. Structure memory alignment often isn’t portable, but bit field memory is even less so.

What i have understood from these statements is that the macros can be used to mask the bits to left or right shift. But i had this doubt in my mind why do they use macros? - I thought by defining it in macros the portability can be established irrespective of 16-bit or 32-bit OS..Is it true?I could not understand the two disadvantages mentioned in the above statement.1.bit fields may be no wider 2.no bit field should overlap the underlying variable boundaries

and the line,

Complex records are usually composed of several contiguous long integers populated with bit-subfield definitions.


1.bit fields may be no wider

Let's say you want a bitfield that is 200 bits long.

struct my_struct {
  int my_field:200;  /* Illegal! No integer type has 200 bits --> compile error!
} v;

2.no bit field should overlap the underlying variable boundaries

Let's say you want two 30 bit bitfields and that the compiler uses a 32 bit integer as the underlying variable.

struct my_struct {
  unsigned int my_field1:30;  
  unsigned int my_field2:30; /* Without padding this field will overlap a 32-bit boundary */
} v;

Ususally, the compiler will add padding automatically, generating a struct with the following layout:

struct my_struct {
  unsigned int my_field1:30;  
  :2  /* padding added by the compiler */
  unsigned int my_field2:30; /* Without padding this field will overlap a 32-bit boundary */
  :2  /* padding added by the compiler */
} v;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜