This blog is under construction

Saturday, 19 May 2012

Bit fields in C

We can specify exact number of bits required for a given data member in a structure using bit fields.  Basically, bit fields avoids the default allocation for a variable by the compiler. Consider a data member named flag in a structure which is of type integer.  If the possible value for flag is either 0 or 1, then we just need 1 bit to store either 1 or 0 in flag. Declaring flag as integer would occupy 32 bits in RAM.  By using bitfield, we can instruct compiler to allocate requested number of bits for a given data member in a structure instead of default size.  Let us see how to use bit fields on data members in a structure.

sizeof operator is not allowed on bit fields.  Please note that the size of the structure will be rounded off to nearest multiple of 4.  In case if the size of the structure is 13 bytes, then the same will be rounded off to 16 bytes.


struct bitfield {
     int flag:1; // allocates only one bit for flag
     char name[7];

The size of above structure bitfield is 8 bytes(1 byte for flag and 7 byte for name).

struct no_bitfield {
     int flag;  // allocates 4 bytes
     char name[8];

The size of above structure no_bitfield is 12 bytes(4 bytes for flag and 8 bytes for name).

Bit field example in C:

  #include <stdio.h>
  struct student1 {
        int age:7;
        int class:3;
        int sex:1;

  struct student2 {
        int age;
        int class;
        int sex;

  int main() {
        int input;
        printf("Enter age for student1(1-100):");
        scanf("%d", &input);
        st1.age = input;
        printf("Enter class value:");
        scanf("%d", &input);
        st1.class = input;
        printf("Enter sex(1-male/0-female):");
        scanf("%d", &input); = input;
        printf("Enter age for student2(1-100):");
        scanf("%d", &st2.age);
        printf("Enter class value:");
        scanf("%d", &st2.class);
        printf("Enter sex(1-male/0-female):");
        scanf("%d", &;
        printf("\n\nStudent1 details:\n");
        printf("Age:%d\nClass:%d\n", st1.age, st1.class);
        printf("\nStudent2 details:\n");
        printf("Age:%d\nClass:%d\n", st2.age, st2.class);
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Enter age for student1(1-100):14
  Enter class value:10
  Enter sex(1-male/0-female):1
  Enter age for student2(1-100):13
  Enter class value:9
  Enter sex(1-male/0-female):0

  Student1 details:
  Student2 details:

No comments:

Post a Comment