# Bit Field - Implementation

Implementation

"A bit field is set up with a structure declaration that labels each field and determines its width." In C and C++ bit fields can be created using unsigned int, signed int, or _Bool (in C99).

You can set, test, and change the bits in the field using a Mask (computing), 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 it's 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;

Obtaining the value of a particular bit can be simply done by left shifting (≪) 0, n amount of times (or, x ≪ n - √x amount of times, where x is a power of 2), where n is the index of the bit you want (the right most bit being the start), e.g. if you want the value of the 4th bit in a binary number, you can do: 0 << 4; which will yield 8, or, 1 << 3; or, 2 << 2; etc. The benefits of this become apparent when iterating through a series of bits one at a time in a for loop, or when needing the powers of large numbers to check high bits.

If a language doesn't 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. Exempli gratia, lets say an int is a 32 bit integer, and it is represented as 32 individual, 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.