Bit fields In C

If in program a variable is to take only two values 1 and 0, we really need only a single bit to store it. Similarly, if a variable is to take values from 0 to 3, then two bits are sufficient to store these values. And if a variable is to take values from 0 through 7, then three bits are sufficient, and if a variable is to take values from 0 through 15, then four bits will be enough, and so on. Why waste an entire integer when one, two, three or four bits will do ? several such data items can be packed into an individual word of memory. To do so, the word is subdivided into individual bit fields. These bit fields are defined as members of a structure. Each bit field can then be accessed individually like any other member of a structure.

The general form of bit – field is

struct tagname 
{
    data – type first number: bit length;
    .  .  .  .  .
    .  .  .  .  .
    data – type last member: bit length;
};

The data – type is either is either int or unsigned word. Remember that a signed bit field should have atleast two bits (Most significant bit will be used as sign bit).

struct test 
{
    unsigned a: 1;
    unsigned b: 4;
    unsigned c: 2;
    unsigned d: 3;
    unsigned e: 1;
};
struct test p;

Figure – illustrates the layout of the bit fields within the word.

img

The internal representation of bit fields is machine dependent. That is, it depends on the size on int and the ordering of the bits. Some machines store bits from left to right and others from right to left.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext