Concept of bit fields

bitwise-operatorsc

Whenever I read a code like this:

  struct node
  {
          int x : 2;
          int p : 4;
   }n;

with bit fields involved, I get really confused, as to how they are represented in memory, what is sizeof(n) etc., how does it differ with normal members of structures? I tried referring K&R and http://en.wikipedia.org/wiki/Bit_field but they little to remove my confusion. What concepts of bit fields am I failing to grasp?

Best Answer

sizeof reports in units of bytes, so it is not well behaved for bit fields.

C doesn't have a clear standard how bit fields have to be laid out, and in general, you should be extremely cautious about any assumptions, especially if different platforms or different compilers may come into play.

I usually use manual packing/unpacking schemes, but hide the details in acessor functions, in those rare circumstances where packing information into integers at the level of bits is appropriate. The only case where the layout of bit fields absolutely does matter is writing drivers for hardware.