Bit Field

Back over on BooleanRepresentation, DaveHarris wrote that Using 1 for true means that true can be stored in a 1-bit BitField

Here's another C idiom for you -- you must be careful when coding for 1-bit bitfields, because they have a portable range of 0, since the compiler may use either signed or unsigned bitfields by default.

I quote from WritingSolidCode, by SteveMaguire: "The bit field does have a non-zero state -- you just don't know what it is. The value can be either -1 or 1 [...]. You can safely use both states of the bit field if you restrict all your comparisons to 0."


Therefore, always explicitly mark 1-bit bit fields as unsigned:

 struct lots_o_flags
   unsigned lottery_won : 1;
   unsigned bridge_closed : 1;
   unsigned some_other_flag : 1;

Note that signed bit-fields might not even be able to contain -1, this is true in computers that use 1-complement for representing signed int's. A signed bit-field that can contain 1 is a bug in the compiler.

-- StephanHouben

BitFields also have the problem that the issue of MSB first or LSB first is undefined. (See ErlangBitSyntax for more).

I always use #define to make bitmasks when I need to do bit-frobbing.

CategoryCee CategoryJargon

View edit of June 7, 2012 or FindPage with title or text search