home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.programming
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!rpi!batcomputer!cornell!ressler
- From: ressler@cs.cornell.edu (Gene Ressler)
- Subject: Re: finding 1st one in integer
- Message-ID: <1992Jul21.194749.25918@cs.cornell.edu>
- Organization: Cornell Univ. CS Dept, Ithaca NY 14853
- References: <Brqu3F.1J4@undergrad.math.waterloo.edu>
- Date: Tue, 21 Jul 1992 19:47:49 GMT
- Lines: 25
-
- In article <Brqu3F.1J4@undergrad.math.waterloo.edu> amichail@cayley.waterloo.edu (Amir Michail) writes:
- >I need a very efficient way of finding the first bit set ( doesn't matter
- >which side ) in a 32 bit integer.
- >
- >For example:
- >
- > binary -> position
- > 1 -> 0
- > 10000 -> 4
- > 1000 -> 3
-
- If `doesn't matter which side' means it's acceptable to find the
- position of the _least_ significant bit set, then a solution
- that's good on 2's complement machines is:
-
- n = (n & -n) - 1;
- /* return the # 1's in n */
-
- You can count the number of 1's in n with any of the amazing
- methods suggested in recent posts. This works because
- in 2's complement, n & -n is the least significant 1 bit of
- n. Subtracting 1 turns it into a string of 1's beneath
- the ls1b.
-
- Gene
-