top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration

Bit fields in C

+4 votes
293 views

bit field is term to store multiple, logical, neighboring bit, where each of the sets of bits, and single bits can be addressed. It is more addressed in C or C language by assigning bitfield to save the memory when we know that only limited number of bits are used in the program.

See the following example 

struct
{
  unsigned int isleft;
  unsigned int isright;
} status;

Above structure will occupy the 2*size of int where we are only using the one bit of each field, so the solution is the bitfield - 

struct
{
  unsigned int isleft : 1;
  unsigned int isright : 1;
} status;

Here we are telling the compiler only one bit (least significant) of each been used so to save memory while running.

 

Syntax

The declaration of a bit-field has the form inside a structure:

struct
{
  type [member_name] : width ;
};

Below the description of variable elements of a bit field:

ElementsDescription
typeAn integer type that determines how the bit-field's value is interpreted. The type may be int, signed int, unsigned int.
member_nameThe name of the bit-field.
widthThe number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type.
 

Memory Comparison 

Without BitField

#include <stdio.h> 

struct my_str 

{

  unsigned int a;

  unsigned int b;

  unsigned int c; 

}; 

int main() 

{

  printf("Size of my_str is %d bytes\n", sizeof(struct my_str));

}

Output

Size of my_str is 12 bytes

 

With Bit Field

#include <stdio.h> 

struct my_str 

{

  unsigned int a : 1;

  unsigned int b : 1;

  unsigned int c : 1; 

}; 

int main() 

{

  printf("Size of my_str is %d bytes\n", sizeof(struct my_str));

}

Output

Size of my_str is 4 bytes
posted Jul 22, 2015 by Salil Agrawal

  Promote This Article
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...