O'Reilly logo

C Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required