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.
Note:
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.
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.
Example:
struct bitfield {
int flag:1; // allocates only one bit for flag
char name[7];
char name[7];
}obj1;
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];
char name[8];
}obj1;
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; }st1; struct student2 { int age; int class; int sex; }st2; 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); st1.sex = 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", &st2.sex); printf("\n\nStudent1 details:\n"); printf("Age:%d\nClass:%d\n", st1.age, st1.class); printf("Sex:%s\n",st1.sex?"Male":"Female"); printf("\nStudent2 details:\n"); printf("Age:%d\nClass:%d\n", st2.age, st2.class); printf("Sex:%s\n",st2.sex?"Male":"Female"); return 0; }
Output:
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:
Age:14
Class:2
Sex:Male
Student2 details:
Age:13
Class:9
Sex:Female
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:
Age:14
Class:2
Sex:Male
Student2 details:
Age:13
Class:9
Sex:Female
No comments:
Post a Comment