What is Bit-field?

A mechanism for declaring a member of a C struct as a field of a given number of bits, as in unsigned int x : 3; Because small values can be packed together, bit-fields are used to group flags and settings. Storing a value that does not fit in an unsigned field leaves the remainder modulo 2 to the power of the field width. Whether fields are laid out from the high or the low end of a word, and whether a field may straddle a boundary, may differ between implementations, so masks and shifts are often used instead to describe peripheral registers or communication formats.

Japanese name: ビットフィールド

Bit-field appears in 2 practice questions across 2 topics, including Embedded Systems & Firmware, C Programming Basics.

Field: C Programming Basics

Try it: questions about Bit-field

When representing peripheral registers with C bit-field structs, what needs care?

  1. ABit fields always make programs twice as fast
  2. BBit ordering and similar details of bit fields are implementation-defined, so another compiler may manipulate unintended bits
  3. CBit fields cannot represent values of 8 bits or more
Show answer and explanation

Answer: B. Bit ordering and similar details of bit fields are implementation-defined, so another compiler may manipulate unintended bits

Bit fields read nicely, but the C standard leaves to the implementation whether bits are allocated from the top or bottom of a unit, how fields crossing boundaries are handled and the access width. Code that works with one compiler may therefore read or write different bits with another compiler or CPU. Headers supplied by microcontroller vendors are usually written with masks and shifts.

Bit-field in the explanations

Questions that mention Bit-field (2)

  1. When representing peripheral registers with C bit-field structs, what needs care?
  2. Which of the following is the output when the code above, which stores 9 in a 3-bit bit-field, is executed?

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

Related terms

struct (C structure) Microcontroller (MCU) Modulo operation Alignment and padding Buffer overflow Dangling pointer Dynamic memory allocation Function pointer Integer promotion Macro (#define)

Back to the glossary