home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.programming
- Path: sparky!uunet!s5!is1.is.morgan.com!is.morgan.com!berlin
- From: berlin@is.morgan.com (Alexander Berlin)
- Subject: Re: finding 1st one in integer
- Message-ID: <1992Jul21.150033@is.morgan.com>
- Sender: news@is.morgan.com
- Nntp-Posting-Host: chico
- Organization: Morgan Stanley - IS
- References: <Brqu3F.1J4@undergrad.math.waterloo.edu> <1992Jul21.173805.12045@bcrka451.bnr.ca>
- Date: Tue, 21 Jul 1992 19:00:33 GMT
- Lines: 53
-
- 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.
- |> >
- |> > For example:
- |> >
- |> > 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).
- |> >
- |> > Amir
- |> >
- |> > P.S. Please do not tell me to use a large lookup table. I know about that.
- |> > I also know that the 68020 and 80386 have instructions to do
- |> this; I want
- |> > portable C code though.
- |>
- |> 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).
- |>
- |> Either use a lookup table of 256 values, or split the byte into two
- |> so that your table is only 16 long.
- |>
- |> If you often have numbers with the 2 lowest bytes clear, you might want to
- |> start by checking 2-byte values against 0.
- |>
- |> 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. :
-
- how about this one line solution:
-
- 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 */
-
- Will work, of course, only when exactly one bit is set. But you want
- efficiency, so there is no unnecessary conditions. And it looks portable -
- doesn't even rely on the int size.
-
- ---
- Alex Berlin
- berlin@is.morgan.com
-