Subject: Re: Bitfields and kernel
To: NetBSD Kernel Technical Discussion List <>
From: Mike Cheponis <mac@Wireless.Com>
List: tech-kern
Date: 09/28/1999 22:04:56
>>[ On Tuesday, September 28, 1999 at 21:17:57 (+0200), m. k. buelow wrote: ]
>> Subject: Re: Bitfields and kernel
>> IMHO, implementing binary flags is best done with constants and
>> the common C idioms of setting or clearing bits.

>On Tue, 28 Sep 1999, Greg A. Woods wrote:
>I would beg to differ, especially when 
>99.9% of all the logic bugs I've ever written had to do with such idioms
>and most of them would never have happened if I'd used bitfields and
>simpler logic tests.

I agree that "The Practice of Programming" by Kernighan & Pike is
excellent book.  Here are some quotes:


"Bitfields are so machine-dependent that no one should use them."


"Don't use C or C++ bitfields; they are highly non-portable and tend to
 generate voluminous and inefficient code.  Instead, encapsulate the
 operations you want in functions that fetch and set individual bits
 within words or an array of words with shift and mask operations.  This
 function returns a group of contiguous bits from the middle of a word:

 /* getbits: get n bits from position p */
 /*  bits are numbered from 0 (least significant) up */

 unsigned int getbits(unsigned int x, int p, int n){
     return (x >> (p+1-n)) & ~(~0 << n);

 If such functions turn out to be too slow, they can be improved with the
 techniques described earlier in this chapter [1].  In C++, operator
 overloading can be used to make bit accesses look like regular subscripting."

[1] Some techniques are replace expensive operations with cheap ones, cache
    frequently used values, precompute results, rewrite in a lower-level
    language, etc.

-Mike Cheponis