home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.sys.mac.programmer
- Path: sparky!uunet!news.univie.ac.at!chx400!bernina!bernina!neeri
- From: neeri@iis.ethz.ch (Matthias Neeracher)
- Subject: Re: (Q) Need bit manipulation algorithm
- In-Reply-To: lim@toadflax.cs.ucdavis.edu's message of 6 Jan 93 10:19:11 GMT
- Message-ID: <NEERI.93Jan6143512@iis.ethz.ch>
- Sender: news@bernina.ethz.ch (USENET News System)
- Organization: Integrated Systems Laboratory, ETH, Zurich
- References: <1993Jan6.022430.19469@leland.Stanford.EDU>
- <1993Jan6.032113.597@planets.risc.rockwell.com>
- <20751@ucdavis.ucdavis.edu>
- Date: Wed, 6 Jan 1993 13:35:12 GMT
- Lines: 44
-
- In article <20751@ucdavis.ucdavis.edu>, lim@toadflax.cs.ucdavis.edu (Lloyd Lim) writes:
-
- > In article <1993Jan6.032113.597@planets.risc.rockwell.com> sho@risc.rockwell.com (Sho Kuwamoto) writes:
- >>
- >>Maybe not the fastest method, but a simple one:
- >> 1) come up with an algorithm which counts the number of
- >> 1's in a given bit pattern. You'll either use a loop
- >> with shifts and increments in it, or you'll use masks.
- >>[...]
-
- > 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?
-
- Sure.
-
- int count_bits(int x)
- {
- /* Return the number of 1 bits in x. Patent pending... NOT! */
- int bitcnt;
-
- for (bitcnt=0; x; ++bitcnt)
- x &= (x-1);
-
- return bitcnt;
- }
-
- For the Pascal heathens out there: If an integer x has n 1-bits (n>1),
- BitAnd(x,x-1) will have (n-1) 1-bits.
-
- Matthias
-
- -----
- Matthias Neeracher neeri@iis.ethz.ch
- "One fine day in my odd past..." -- Pixies, _Planet of Sound_
-