🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.compression.research
Article #20

Re: Algorithm for finding set bits in a bit-string (and MSB).

#20
From: Alan Wm Paeth
Date: Mon, 03 Aug 1992 23:53
22 lines
1572 bytes
An elegant and efficient MSB-finding algorithm has been forwarded to me by
Dean Inada (dmi@peregrine.com). It has a constant running time proportional
to Log2(machine int size):

>msbpos(i)
>    {
>    int p = 0;
>    if (i & 0xAAAAAAAA  >  i &  0x55555555    ) p++;
>    if (i & 0xCCCCCCCC  >  i &  0x33333333    ) p += 2;
>    if (i & 0xF0F0F0F0  >  i &  0x0f0f0f0f    ) p += 4;
>    if (i & 0xFF00FF00  >  i &  0x00ff00ff    ) p += 8;
>    if (i & 0xFFFF0000  >  0 /* 0x0000xxxx */ ) p += 16;
>    return(p);

The recursive derivation is not immediately obvious but resembles priority
encoder designs. The logical bit-sieve takes advantage of arithmetic inequality
of two integers A, B: if A >= B then msbpos(A) >= msbpos(B), though note that
exact equality '=' may not replace the '>='. A companion "lsbpos" routine bit
reverses its input then continus with msbpos(). Bit reversal hardware is common
on machines designed to support the FFT.

    /Alan Paeth
Technical Details
Message-ID: <BsFMD4.HAI@watcgl.uwaterloo.ca>
Path: arc1-ca.pugleaf.net!sparky!uunet!utcsri!torn!watserv2.uwaterloo.ca!watmath!watcgl!watpix.waterloo.edu!awpaeth
References: <Bs3yBx.7AA@watserv1.uwaterloo.ca> <Bs46JC.35n@watcgl.uwaterloo.ca> <1992Aug3.164044.28037@m.cs.uiuc.edu>

Show Full Headers
Complete Article Headers
Newsgroups: comp.compression.research,comp.arch,comp.lang.c
Path: arc1-ca.pugleaf.net!sparky!uunet!utcsri!torn!watserv2.uwaterloo.ca!watmath!watcgl!watpix.waterloo.edu!awpaeth
From: awpaeth@watpix.waterloo.edu (Alan Wm Paeth)
Subject: Re: Algorithm for finding set bits in a bit-string (and MSB).
Message-ID: <BsFMD4.HAI@watcgl.uwaterloo.ca>
Sender: news@watcgl.uwaterloo.ca (USENET News System)
Organization: University of Waterloo
References: <Bs3yBx.7AA@watserv1.uwaterloo.ca> <Bs46JC.35n@watcgl.uwaterloo.ca> <1992Aug3.164044.28037@m.cs.uiuc.edu>
Date: Mon, 3 Aug 1992 23:53:28 GMT
Lines: 22