Bit Fields

The second method of manipulating bits is to use a bit field, which is just a set of neighboring bits within a signed int or an unsigned int. (C99 additionally allows type _Bool bit fields.) A bit field is set up with a structure declaration that labels each field and determines its width.

For example, the following declaration sets up four 1-bit fields:

struct   {
         unsigned int autfd   : 1;
         unsigned int bldfc   : 1;
         unsigned int undln   : 1;
         unsigned int itals   : 1;
} prnt;

This definition causes prnt to contain four 1-bit fields. Now you can use the usual structure membership operator to assign values to individual fields:

prnt.itals = 0;
prnt.undln = 1;

Because each of these particular fields is just 1 bit, 1 and 0 are the only values ...

Get C Primer Plus, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.