Bit field

From ArticleWorld


A bit field is a commonly-used data structure that used to compactly hold a set of Boolean flags. Instead of using Boolean variables for each flag, the flags are stored in a fixed-size data structure like an integer, whose size in bits is known. The Boolean flags are then stored in each bit of the data structure, minimizing memory usage.

In order to retrieve, read and write information from and to a bit field, the programmer uses the bitwise operators AND, OR and NOT.

Many beginners confuse (and incorrectly use) bit fields and bit arrays. It should be noted that bit fields are only used to store small amounts of data that is not indexed. Bit arrays, on the other hand, are much longer sequences of bits that are indexed and often with a bit-width larger than other basic data structures of the program.

Some programming languages explicitly support turning a basic data type like an integer to a data field, facilitating this operation. This is C's case.

Example

A simple C example is following. What you can see above is the general implementation, that does not make use of C's facilities for bit field usage.

#define CATEGORY_PROGRAMMING_LANGUAGES ((unsigned char)0x01)
#define CATEGORY_OOP_LANGUAGES	       ((unsigned char)0x02)
#define CATEGORY_PROCEDURAL_LANGUAGES  ((unsigned char)0x03)
#define CATEGORY_FUNCTIONAL_LANGUAGES  ((unsigned char)0x04)

unsigned char article_type;

/*Set this article as belonging to the Programming Languages category*/

article_type = article_type | CATEGORY_PROGRAMMING_LANGUAGES;

/*This article is also about a procedural programming language*/

article_type = article_type | CATEGORY_PROCEDURAL_LANGUAGES

/*Let's see if this is about a functional language*/

printf("%d \n", article_type & CATEGORY_FUNCTIONAL_LANGUAGES);

/*Let's see if this is about a procedural language*/

printf("%d \n", article_type & CATEGORY_PROCEDURAL_LANGUAGES);

/*More of the program comes here*/

/*Now let's suppose the article has changed. It is no longer about a procedural language so we have to reset the relevant bits to 0*/

article_type = article_type & ~CATEGORY_PROCEDURAL_LANGUAGE;

/*Let's see if this is about a procedural language again*/

printf("%d \n", article_type & CATEGORY_PROCEDURAL_LANGUAGES);

When ran, the above piece of code will display the following sequence:

1
0
0