Bit field

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In computer science, a bit field is a sequence of bits, typically contained within a single machine word. Bit fields generally represent small integers (signed or unsigned), enumerated types, booleans, or flag fields.

Some programming languages support bit fields directly, typically as an annotation on a record field.

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.

Implementation[edit]

In C and derived languages, a bit field is declared as an annotation on the fields of a struct.[1]

Bits can be set, tested, and changed using a mask, bitwise operators, and the proper membership operator of a struct (. or ->). ORing a value will turn the bits on if they are not already on, and leave them unchanged if they are, e.g. bf.flag |= MASK; To turn a bit off, you can AND its reciprocal, e.g. bf->flag &= ~MASK; And finally you can toggle a bit (turn it on if it is off and off if it is on) with the XOR operator, e.g. bf->flag ^= MASK; To test a bit you can use an AND expression, e.g. (flag_set & MASK) ? true : false;

To pragmatically compute the mask to use in any of the aforementioned bitwise operators the left shift (<<) operator can be used. For instance, to check if the least significant bit is set, use (byte) & 1 << 0 (or simply 1), where (byte) is a variable to query. To check if the second least significant bit is set, use (byte) & 1 << 1. Generally, use (byte) & 1 << (N-1) to query the Nth least significant bit in (byte).

If a language does not support bit fields, but supports bit manipulation, you can do something very similar. Since a bit field is just a group of neighboring bits, and so is any other primitive data type, you can substitute the bit field for a primitive, or array of primitives. For example, with a 32 bit integer represented as 32 contiguous bits, you could use it the same way as a bit field with one difference; with a bitfield you can represent a particular bit or set of bits using its named member, and a flag whose value is between 0, and 2 to the nth power, where n is the length of the bits.

Examples[edit]

Declaring a bit field in C:

struct box_props
{
     unsigned int opaque       : 1;
     unsigned int fill_color   : 3;
     unsigned int              : 4; // fill to 8 bits
     unsigned int show_border  : 1;
     unsigned int              : 0; // Pad to next natural boundary (implementation defined)
     unsigned int border_color : 3;
};

See also[edit]

References[edit]

  1. ^ Prata, Stephen (2007). C primer plus (5th ed.). Indianapolis, Ind: Sams. ISBN 0-672-32696-5. 

External links[edit]