C Bit Fields

In C, the size of union or struct members can be stated in bits. Bit fields allow users to manage memory efficiently by letting them explicitly declare a data member in bits. Allowable data types for a bit field include qualified and unqualified signed int, and unsigned int.

Note, the sizeof() operator will not work on bit fields.

Syntax

struct label {
    datatype var : no_of_bits;
};

Restrictions of Bit Fields

  • You cannot define an array of bit fields
  • Take the address of a bit field
  • Have a pointer to a bit field
  • Have a reference to a bit field

Example Code

#include<stdio.h>

struct fan {
    //Remember length is in bits. 8 bit = 1 byte
    unsigned int no_of_blades : 3;
    unsigned int speed : 3;
    unsigned int price : 16;
};

int main(void)
{
    struct fan table_fan;
	
    table_fan.no_of_blades = 3;
    table_fan.speed = 4;
    table_fan.price = 1000;
    
    printf("sizeof table_fan = %d bytes\n", sizeof(table_fan));
	   	
    printf("table_fan.no_of_blades = %u\n",table_fan.no_of_blades);
    printf("table_fan.speed = %u\n",table_fan.speed);
    printf("table_fan.price = %u\n",table_fan.price);
	
    return 0;
}

Output

sizeof table_fan = 4 bytes
table_fan.no_of_blades = 3
table_fan.speed = 4
table_fan.price = 1000

Zero-width Bit Field

Bit fields with a length of 0 must be unnamed. Unnamed bit fields cannot be referenced or initialized. A zero-width bit-field aligns the next field to the boundary (by padding bits) defined by the datatype of the bit-field.

Zero-width Bit Field Example

#include<stdio.h>

struct A {
    int var1 : 2;
    int var2 : 6;
};

struct B {
    int var1 : 2;
    int : 0;
    int var2 : 6;
};

int main()
{
    struct A a;
    struct B b;
    printf("sizeof a = %d\n", sizeof(a));
    printf("sizeof b = %d\n", sizeof(b));    
    
    return 0;
}

Output

sizeof a = 4
sizeof b = 8

Trending

C Programming

Remember to follow community guidelines and don't go off topic.