C Bit Fields

In this tutorial you will learn about the C Bit Fields and its application with practical example.

In C Programming Language we have the option to store integer members into memory spaces smaller than the compiler would ordinarily allow. These can be achieved using the space-saving structure members are called bit fields, and their width in bits can be explicitly declared.

Table Of Contents−

This is very useful especially when memory or data storage is at a premium. A bit field is set up with a structure declaration that labels each field and determines its width.

Bit Field Declaration

A bit-field declaration contains a type specifier followed by an optional member_name, a colon, a constant integer expression that indicates the field width in bits, and a semicolon.

Bit fields with a width of 0 must be unnamed. Unnamed bit-fields cannot be referenced or initialized. If a series of bit fields do not makeup up the size of an int, padding can take place.

The following example demonstrates padding. Suppose that an int occupies 4 bytes. The example declares the identifier room to be of type struct app_state:

The structure room contains eight members with a width of 16 bytes. The following table describes the storage that each member occupies:

Member Name Storage Occupied
light 1 bit
fan 1 bit
(padding — 30 bits) To the next int boundary
count The size of an int (4 bytes)
ac 4 bits
(unnamed field) 4 bits
clock 1 bit
(padding — 23 bits) To the next int boundary (unnamed field)
flag 1 bit
(padding — 31 bits) To the next int boundary

You can not access the field by direct its name.

Syntax:

We can access the member “light” as “room. light”, The following expression sets the light field to 1

When you assign to a bit field a value that is out of its range, the bit pattern is preserved and the appropriate bits are assigned. The following expression sets the “fan” field of the room structure to a 0 (zero) because only the least significant bit is assigned to the fan field:

Note:- The maximum bit field length is 64 bits. For portability, do not use bit fields greater than 32 bits in size.

 

In this tutorial we have learn about the C Bit Fields and its application with practical example. I hope you will like this tutorial.