Bit field
From Wikipedia, the free encyclopedia
A bit field is a common idiom used in computer programming to store a set of Boolean datatype flags compactly, as a series of bits. The bit field is stored in an integral type of known, fixed bit-width. Each Boolean flag is stored in a separate bit. Usually the source code will define a set of constants, each a power of two, that semantically associate each individual bit with its respective Boolean flag. The bitwise operators AND, OR, and NOT are used in combination to set, reset and test the flags.
A bit field is distinguished from a bit array in that the latter is used to store a large set of bits indexed by integers and is often wider than any integral type supported by the language. Bit fields, on the other hand, typically fit within a machine word, and the denotation of bits is independent of their numerical index.
[edit] Examples
Example implementation in C:
#define PREFERENCE_LIKES_ICE_CREAM ((unsigned char) (1 << 0)) // 0x01 #define PREFERENCE_PLAYS_GOLF ((unsigned char) (1 << 1)) // 0x02 #define PREFERENCE_WATCHES_TV ((unsigned char) (1 << 2)) // 0x04 #define PREFERENCE_READS_BOOKS ((unsigned char) (1 << 3)) // 0x08 unsigned char preference; void setPreference(unsigned char flag) { preference |= flag; } void resetPreference(unsigned char flag) { preference &= ~flag; } unsigned char getPreference(unsigned char flag) { return (preference & flag) != 0; }
Instead of using hardcoded numerical representations for the powers of two (0x08), the use of the Bit Shift operator (1 << 3) with an incrementing shift operand is recommended for easier readability.
Kernighan and Ritchie's book, The C Programming Language, describes a method for defining and accessing fields directly. Using this method, the use of bitwise operators is not needed as bit members can be accessed the same as struct members. An example using a struct follows:
struct preferences { unsigned int likesIceCream : 1; unsigned int playsGolf : 1; unsigned int watchesTV : 1; unsigned int readsBooks : 1; }; struct preferences fred; fred.likesIceCream = 1; fred.playsGolf = 1; fred.watchesTV = 1; fred.readsBooks = 0; if (fred.likesIceCream == 1) { ...
However, bit members in structs have practical drawbacks. First, the ordering of bits in memory varies from compiler to compiler. In addition, many popular compilers generate inefficient code for reading and writing bit members. Thus bitwise operators remain in wide use in programs in the C and C++ languages as of 2006.
[edit] See also
[edit] External links
- Bit field, a simple C example.