Article View: comp.compression.research
Article #19Re: Algorithm for finding set bits in a bit-string (and MSB).
From: Don Gillies
Date: Mon, 03 Aug 1992 16:40
Date: Mon, 03 Aug 1992 16:40
27 lines
1736 bytes
1736 bytes
What about using this algorithm to find the lowest bit set in a word
if (p & (p-1)) return(-1); /* returns -1 if > 1 bit set */
return(bitcount(p ^ (p-1))); /* use XOR, returns 32 if no bit set */
where bitcount counts the number of bits in a word? bitcount exists
in the hardware of several cdc machines and elsewhere. On other
machines, it can be implemented in 16 arithmetic ops or much less if
the computer has a fast % (remainder) operation. For instance, on the
68020 % is slow enough that the arithmetic bitcount() subroutine is
faster. In fact, arithmetic bitcount can run faster than 8-bit
character lookups (assuming a memory lookup is 2 cycles, whereas an
arithmetic op is one cycle). Table lookups only win with 16-bit
tables:
bitcount(n)
long unsigned n;
{
long unsigned tmp;
tmp = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111);
tmp = ((tmp + (tmp >> 3)) & 030707070707);
tmp = (tmp + (tmp >> 6));
tmp = (tmp + (tmp >> 12) + (tmp >> 24)) & 077;
/* 6+3+3+5 = 16 ops */
--
Technical Details
Message-ID:
<1992Aug3.164044.28037@m.cs.uiuc.edu>Path:
arc1-ca.pugleaf.net!sparky!uunet!cs.utexas.edu!sun-barr!ames!haven.umd.edu!darwin.sura.net!mips!sdd.hp.com!ux1.cso.uiuc.edu!m.cs.uiuc.edu!gilliesReferences:
<1992Jul26.010325.9885@infonode.ingr.com> <MOSS.92Jul25222337@ibis.cs.umass.edu> <Bs3yBx.7AA@watserv1.uwaterloo.ca> <Bs46JC.35n@watcgl.uwaterloo.ca>Show Full Headers
Complete Article Headers
Newsgroups: comp.compression.research,comp.arch,comp.lang.c Path: arc1-ca.pugleaf.net!sparky!uunet!cs.utexas.edu!sun-barr!ames!haven.umd.edu!darwin.sura.net!mips!sdd.hp.com!ux1.cso.uiuc.edu!m.cs.uiuc.edu!gillies From: gillies@m.cs.uiuc.edu (Don Gillies) Subject: Re: Algorithm for finding set bits in a bit-string (and MSB). Message-ID: <1992Aug3.164044.28037@m.cs.uiuc.edu> Organization: University of Illinois, Dept. of Comp. Sci., Urbana, IL References: <1992Jul26.010325.9885@infonode.ingr.com> <MOSS.92Jul25222337@ibis.cs.umass.edu> <Bs3yBx.7AA@watserv1.uwaterloo.ca> <Bs46JC.35n@watcgl.uwaterloo.ca> Date: Mon, 3 Aug 1992 16:40:44 GMT Lines: 30