C Bit Field

Advertisements

Bit Field in C

Bit field can be used to reduce memory consumption when it is known that only some bits would be used for a variable. Bit fields allow efficient packaging of data in the memory.

As we know, integer takes two bytes(16-bits) in memory. Some times we need to store value that takes less then 2-bytes. In such cases, there is wastages of memory. For example, if we use a variable temp to store value either 0 or 1. In this case only one bit of memory will be used rather then 16-bits. By using bit field, we can save lot of memory.

Syntax for bit field


              struct struct-name
              {
                     datatype var1 : size of bits;
                     datatype var2 : size of bits;
                     - - - - - - - - - -
                     - - - - - - - - - -
                     datatype varN : size of bits;
              };

Example for bit field


              #include<stdio.h>

              struct info1
              {
                     int num;
              };

              struct info2
              {
                     int num : 1;
              };

              void main()
              {

                 struct info1 f1;
                 struct info2 f2;


                 printf("\n\n\tSize of info1 is : %d",sizeof(info1));
                 printf("\n\n\tSize of info2 is : %d",sizeof(info2));

              }

   Output :

              Size of info1 is : 2
              Size of info2 is : 1

           

Related topics

Advertisement