Bit field in C

What is Bit field in C?

Bit field in C defines a state of the size of your structure (struct) or union members in the form of bits. This concept is to because of efficiently utilizing the memory when you know that your amount of a field or collection of fields is not going to exceed a specific limit or is in-between the desired range.

 

Bit field representation

Declarating Bit field

Variables that are defined using a predefined width or size are called bit fields. This bit field can leave more than a single bit,

 

Syntax

struct 
{
 data - type[nameofmember]:
 width_of_Bit - field; 
};

Description

Data Type
An integer type that determines how a bit-field’s value is interpreted. The type may be int, signed int, or unsigned int.

Name of member

Defines the name of the bit-field member within the structure

Width

The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type.

 

Program

#include <stdio.h>
 
// A structure without forced alignment
struct test1 {
    unsigned int x : 5;
    unsigned int y : 8;
};
 
// A structure with forced alignment
struct test2 {
    unsigned int x : 5;
    unsigned int : 0;
    unsigned int y : 8;
};
 
int main()
{
    printf("Size of test1 is %lu bytes\n",
           sizeof(struct test1));
    printf("Size of test2 is %lu bytes\n",
           sizeof(struct test2));
    return 0;
}

Output

Size of test1 is 4 bytes
Size of test2 is 8 bytes

 

Need for Bit Fields in C

Bit fields are of great significance in C programming, because for the following reasons:

      • Used to reduce memory consumption.
      • Easy to implement.
      • Provides flexibility to the code.

 

Also, read the Double pointer in C

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *