home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!usc!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!ames!think.com!unixland!public!peterk
- From: peterk@public.sub.org (Peter Kittel)
- Newsgroups: comp.programming
- Subject: Re: finding 1st one in integer
- Message-ID: <1992Jul22.121859.12676@public.sub.org>
- Date: 22 Jul 92 12:18:59 GMT
- References: <Brqu3F.1J4@undergrad.math.waterloo.edu> <1992Jul21.173805.12045@bcrka451.bnr.ca> <1992Jul21.150033@is.morgan.com>
- Organization: Public News & Mailserver, Commodore Germany PM UNIX, Frankfurt
- Lines: 56
-
- berlin@is.morgan.com (Alexander Berlin) writes:
- >In article <1992Jul21.173805.12045@bcrka451.bnr.ca>, sjm@bcrki65.bnr.ca (Stuart MacMartin) 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.
- >|> >
- >|> > binary -> position
- >|> > 1 -> 0
- >|> > 10000 -> 4
- >|> > 1000 -> 3
- >|> >
- >|> > One can make the simplifying assumption that only 1 bit will be
- >|> > set in the 32 bit integer (if that helps).
- >|>
- >|> Check a byte at a time for non-zero (being careful not to assume byte
- >|> ordering or behaviour of shifting signed values if you want to be portable).
-
- Sounds like a good advice. This makes 4 comparisons in the outer loop.
-
- >|> Either use a lookup table of 256 values, or split the byte into two
- >|> so that your table is only 16 long.
-
- Why tables? We *have* bit operators in C!
-
- >|> If you often have numbers with the 2 lowest bytes clear, you might want to
- >|> start by checking 2-byte values against 0.
-
- Or even simpler, as very first action, compare with 65536.
-
- >how about this one line solution:
-
- It's a bit slow, I fear, he asked for an *efficient* way.
-
- >unsigned int i; /* given integer */
- >unsigned int j; /* working variable */
- >int bitset; /* result */
-
- > for(j=1, bitset=1; ; bitset++, j+=j) if (i==j) break; /* sets bitset */
-
- And you run the loop from the wrong side, he searches the first bit from
- left! So how about this:
-
- if (i>65535) /* upper or lower 16 bits? */
- { for (bitset=31; bitset>15; bitset--) if (i & (1<<bitset)) break; }
- else
- { for (bitset=15; bitset>=0; bitset--) if (i & (1<<bitset)) break; }
-
- For gaining even more speed you could do more outer if's for bytes and
- nibbles and so on, building a binary tree (but can't imagine a simple
- loop statement to do this sort of binary search).
-
- --
- Best regards, Dr. Peter Kittel // E-Mail to \\ Only my personal opinions...
- Commodore Frankfurt, Germany \X/ {uunet|pyramid|rutgers}!cbmvax!cbmger!peterk
- or peterk@public.sub.org
-