- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain bit field in C language by using structure concept
Bit field is used for specifying the size of variable in terms of bits. Generally, it is defined inside a structure.
- Bit field: 1 byte=8 bits
For example,
An example is explained below −
Struct info{ int x:2; };
Here, x is occupying 2bits.
It is invalid to assign any value to a bit field out of its range.
We cannot use scanf statements to input the value of bit field because, size of and address operator cannot apply to bit field.
The data types that we can assign to a bit field can be int, signed int, unsigned int.
Program
Following is the C program for unsigned int −
#include<stdio.h> struct info{ unsigned int x:3;// assign bit field to unsigned int inside structure }; main(){ struct info i; i.x=8; printf("%d",i.x); }
Output
The output is as follows &miuns;
0
Explanation
Range formula for unsigned int is 0 to 2n-1 and n=no of bits.
Here, n=3, i.e., unsigned int is in between 0 to 23 -1, which is equal to 0 to 7.
Program
Refer the program given below for int −
#include<stdio.h> struct info{ int x:3;// assign bit field to int inside structure }; main(){ struct info i; i.x=4; printf("%d",i.x); }
Output
You will get the following output −
-4
Explanation
- Range formula for signed int = (-2(n-1)+1) to 2n-1, where n is no of bits.
- In the program, n=3
- Substitute this in the formula and we have the following result −
=(-2(3-1)+1) to 23-1 =(-22+1) to 22 = -3 to 4 i.e., -3,-2,-1,0,1,2,3,4,
- Related Articles
- Explain the concept of Sorting in C language
- Explain the concept of stack in C language
- Explain the concept of pointers in C language
- Explain the concept of Arithmetic operators in C language
- Explain the concept of pointer accessing in C language
- Explain the concept of Linked list in C language
- Explain linear data structure queue in C language
- Explain the concept of union of structures in C language
- Explain the concept of Uninitialized array accessing in C language
- Explain the concept of one and two dimensional array processing using C language
- Explain queue by using linked list in C language
- Explain the accessing of structure variable in C language
- Explain the concept of logical and assignment operator in C language
- Explain the insertion sort by using C language.
- Demonstrate the concept of pointers using C language
