home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.sys.mac.programmer
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!uwm.edu!ux1.cso.uiuc.edu!news.cs.indiana.edu!umn.edu!csus.edu!netcom.com!norm
- From: norm@netcom.com (Norman Hardy)
- Subject: Re: (Q) Need bit manipulation algorithm
- Message-ID: <1993Jan9.212559.5319@netcom.com>
- Organization: Netcom Online Communications Services (408-241-9760 login: guest)
- References: <1993Jan6.022430.19469@leland.Stanford.EDU> <1993Jan6.032113.597@planets.risc.rockwell.com> <20751@ucdavis.ucdavis.edu>
- Date: Sat, 9 Jan 1993 21:25:59 GMT
- Lines: 26
-
- In article <20751@ucdavis.ucdavis.edu> lim@toadflax.cs.ucdavis.edu (Lloyd Lim) writes:
- >
- >There is a neat trick for counting the number of bits in a word that
- >a Microsoft geek showed me one time. If there are k bits with 1's,
- >it runs in O(k) time.
- >
- >I don't remember the algorithm, but it involved subtracting 1 and could
- >be written in one line of C. (Yeah, I know... You could write anything,
- >even Microsoft Word, in one very long line of C code. Come to think of it,
- >that's probably what they did.) The subtraction was used to create
- >instant masks: e.g. 0x0100 - 1 = 0x00FF. It went from the highest 1 bit
- >to the lowest, magically avoiding all of the 0's.
- >
- >That's all I remember. Anyone remember this algorithm?
- >
- >+++
- >Lloyd Lim Internet: lim@cs.ucdavis.edu
- >Lim Unlimited America Online: LimUnltd
- >330 W. Iris Ave. AppleLink: LimUnltd
- >Stockton, CA 95210-3738 CompuServe: 72647,660
- There are several versions much like the following:
-
- #include <stdio.h>
- int main(){int K; for(K=-4; K<15; ++K)
- {int j=0, k=K; while(k) {k = k-1 & k; ++j;}
- printf("There are %d ones in %d.\n", j, K);}}
-