home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.programming
- Path: sparky!uunet!newsgate.watson.ibm.com!yktnews!admin!flu!lowry
- From: lowry@watson.ibm.com (Andy Lowry)
- Subject: Re: finding 1st one in integer
- Sender: news@watson.ibm.com (NNTP News Poster)
- Message-ID: <LOWRY.92Jul21165844@rotor.watson.ibm.com>
- In-Reply-To: amichail@cayley.waterloo.edu's message of Tue, 21 Jul 1992 14:40:26 GMT
- Date: Tue, 21 Jul 1992 21:58:44 GMT
- Disclaimer: This posting represents the poster's views, not necessarily those of IBM
- References: <Brqu3F.1J4@undergrad.math.waterloo.edu>
- Nntp-Posting-Host: rotor.watson.ibm.com
- Organization: IBM T.J. Watson Research Center
- Lines: 37
-
- 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];
- }
-
- The idea is that you want to use a table lookup, but not on the entire
- sparse range 1-2^31, so you need to find a hash function that will map
- the set {2^n: 0 <= n <= 31} uniquely to a reasonably dense range of
- integers. Using remainder modulo 37 does the trick, and the table
- above was generated by a trivial C program. The -1 entries are
- unused.
-
- There's probably some algebraic way of predicting what divisor to use
- instead of 37 to get the minimum sized table for a given "word size,"
- but I'll leave that for somebody else to fill in. I just started with
- 33 and tried successive numbers until one worked. But I don't believe
- it can be a coincidence that 37 is the least prime greater than 32!
- --
- Andy Lowry, lowry@watson.ibm.com, (914) 784-7925
- IBM Research, P.O. Box 704, Yorktown Heights, NY 10598
-