Bit field (source code)

= Bit field

A \b[bit field] assigns a selected group of <bits> within a stored value to a particular component or meaning. For a contiguous field, specify its width $n$, starting position $s$ counted from the least significant bit, and interpretation. In a <pixel format>, separate bit fields can hold red, green and blue component codes. The Linux frame-buffer interface describes such fields with explicit offset and length members.<The Frame Buffer Device API in the Linux Kernel documentation>[Section4, fb_bitfield and non-overlapping component fields]{ref}

For a nonnegative integer word $W$, the unsigned value of the field is
$$
v=\left\lfloor\frac{W}{2^s}\right\rfloor\bmod2^n.
$$
In a language with the usual unsigned <bitwise operations>, this corresponds to shifting right by $s$ and applying <bitwise AND> with $2^n-1$.

For an original eight-bit example, let $W=181$, written `0xB5` or binary `10110101`. Select three bits beginning at position 4, so the field consists of bits 6–4. Extraction gives
$$
v=\lfloor181/16\rfloor\bmod8=11\bmod8=3.
$$
The field's bits are `011`. To replace them by value 6, clear the field with mask `0x70`, then insert `6 << 4`. Restricted to eight-bit words, the calculation is
$$
W'=(W\mathbin{\&}\mathtt{0x8F})\mathbin{|}\mathtt{0x60}
=\mathtt{0x85}\mathbin{|}\mathtt{0x60}
=\mathtt{0xE5}.
$$
The other five bits are unchanged. The range $0\leq v<2^n$ specifies what fits in an unsigned field.

A language-level bit-field declaration is a related abstraction, but its physical placement follows that language and implementation. In the <C programming language>, `unsigned int code : 3;` declares a three-bit field; C11 leaves allocation order within a storage unit implementation-defined and the storage unit's alignment unspecified.<C11 committee draft N1570>[Section6.7.2.1, paragraphs10–11, printed p114]{ref} Such a declaration alone therefore does not specify a portable external byte sequence. An explicit layout must also state the relevant <endianness> and storage rules.