-->

Bit Fields

Bit Fields

·         We have been using integer words of size 16 bits to store data.
·         There are occasions where data items require much less than 16 bits space, in such cases we waste memory space
·         C language permits us to use small bit fields to hold data items and thereby to pack several data items in a word of memory.
·         Bit fields allow direct manipulation of strings of preselected bits as if it is represented as an integral quantity.
·         A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length.
·         A word can therefore be divided into a number of bit fields.
·         The name and size of bit fields are defined using a structure.
·         Bit field definition:
struct tag-name
{
data-type name 1 :bit-length;
data-type name 2 :bit-length;
data type name n:bit-length;
}
·         The data-type is either int or unsigned int or signed int and the bit-length is the number of bits used for the specified name.
·         Field name should be followed by a colon.
·         Signed bit field should have at least 2 bits (one bit for sign).
·         The bit-length is decided by the range of values to be stored.
·         The largest value that can be stored is 2n-1, where 'n' is the bit-length.
·         The internal representation of a bit field is machine dependent i.e. it depends on the size of int and the ordering of bits.
·         Some machines store bits from left to right and others from right to left.
·         Here, the diagram below illustrates the layout of bit fields assuming a 16-bit word that is ordered from right to left( most significant bit in left most).
i)        The first field always starts with the first bit of the word.
ii)       A bit field can't overlap integer boundaries. i.e. the sum of lengths of all the fields in a structure should not be more than the size of a word. In case it is more, the overlapping field is automatically forced to the beginning of the next word.
iii)     There can be unnamed fields declared with size. Example: unsigned : bit - length Such fields provide padding within the words.
iv)     There can be unused bits in a word.
v)      We can't take the address of a bit field variable it means that, Q we cannot use scanf to read values into bit fields. 9 we can neither use pointers to access the bit fields.
vi)     Bit fields cannot be arranged.
vii) Bit fields should be assigned values within the range of their size. If we try to assign larger values, behaviour would be unpredictable. 

Related Posts

Subscribe Our Newsletter