home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.programming
- Path: sparky!uunet!utcsri!torn!cunews!nrcnet0!bnrgate!bcrka451!bcrki65!sjm
- From: sjm@bcrki65.bnr.ca (Stuart MacMartin)
- Subject: Re: finding 1st one in integer
- Message-ID: <1992Jul22.140938.27938@bcrka451.bnr.ca>
- Sender: 5E00 Corkstown News Server
- Reply-To: sjm@bcrki65.bnr.ca (Stuart MacMartin)
- Organization: Bell-Northern Research, Ottawa, Canada
- References: <LOWRY.92Jul21165844@rotor.watson.ibm.com> <Brqu3F.1J4@undergrad.math.waterloo.edu>
- Date: Wed, 22 Jul 1992 14:09:38 GMT
- Lines: 46
-
- In article <LOWRY.92Jul21165844@rotor.watson.ibm.com>,
- lowry@watson.ibm.com (Andy Lowry) writes:
- > 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.
- >
- > > One can make the simplifying assumption that only 1 bit will be
- > > set in the 32 bit integer (if that helps).
- >
- > This seems to work nicely:
- >
- > int firstone(x)
- > unsigned int x;
- > {
- > static int keys[] = {
- > -1, 0, 1, 26, 2, 23, 27, -1, 3, 16,
- > 24, 30, 28, 11, -1, 13, 4, 7, 17, -1,
- > 25, 22, 31, 15, 29, 10, 12, 6, -1, 21,
- > 14, 9, 5, 20, 8, 19, 18 };
- >
- > return keys[x % 37];
- > }
- >
-
- Very nice.
-
- The difference between this and the one I (and another) suggested
- is that this one relies on only one bit being set, whereas my solution was
- more general and did not use the simplifying assumption. This one ought to
- be faster, although the % is slow on some machines. So the choice really
- comes down to: do you want to make the simplifying assumption, or are you
- going to want to use the same routine later in a case that has more than
- one bit set? This example is so trivial that you would implement both when
- needed, but sometimes it is better to write routines slightly more general
- than you need if this does not make a *noticeable* difference in performance.
-
- About >>=: Yes this is portable *if* the value is unsigned. If the value
- is signed, then this might do either logical or arithmetic shifting.
-
- Stuart
-
- : Stuart MacMartin email: sjm@bnr.ca :
- : Bell-Northern Research phone: (613) 763-5625 :
- : PO Box 3511, Stn C, Ottawa, K1Y-4H7, CANADA Standard disclaimers apply. :
-