April 30, 2012

Bitfields C - strength and weakness

Bitfields are powerful and widely used (mostly in embedded) although they introduce some limitations.

  • You can't apply address operator to bitfield because they operate on bits not bytes. 
  • They are always converted to the int type for computation.
  • If you use signed int, be aware of the range of values for the defined type. Signed int a:1 has a value 0 or -1 not 1 !
  • C language gives no guarantee of the ordering of fields within machine words. The packing order are implementation defined.

More reading about this topic in following sites:

Understanding bit fields c [linuxforu.com]

C bitfields [cs.cf.ac.uk/Dave]

Working with bits and bitfields [coranac.com]

Bitfields Endianness [mjfrazer.org/mjfrazer]

Bitfields Aligment [keil.com/support]