home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / programm / 2094 < prev    next >
Encoding:
Text File  |  1992-07-23  |  1.0 KB  |  35 lines

  1. Newsgroups: comp.programming
  2. Path: sparky!uunet!tarpit!bilver!alex
  3. From: alex@bilver.uucp (Alex Matulich)
  4. Subject: Re: finding 1st one in integer
  5. Organization: W. J. Vermillion - Winter Park, FL
  6. Date: Fri, 24 Jul 1992 03:01:58 GMT
  7. Message-ID: <1992Jul24.030158.15492@bilver.uucp>
  8. References: <Brqu3F.1J4@undergrad.math.waterloo.edu>
  9. Lines: 24
  10.  
  11. amichail@cayley.waterloo.edu (Amir Michail) writes:
  12. >I need a very efficient way of finding the first bit set ( doesn't matter
  13. >which side ) in a 32 bit integer. 
  14.  
  15. How about this one?  It finds the position of the high-order bit, and it
  16. works even if more than 1 bit is set.
  17.  
  18. int firstbit(int n)
  19. {
  20.    int i = 0, j;
  21.    while ( (j = n << 1) > n) {
  22.       ++i;
  23.       n = j;
  24.    }
  25. return i;
  26. }
  27.  
  28. This function will return a number that assumes bit 0 is the high-order bit.
  29.  
  30. -- 
  31.  _ |__  Alex Matulich
  32.  /(+__>  Unicorn Research Corp, 4621 N Landmark Dr, Orlando, FL 32817
  33. //| \     UUCP:  alex@bilver.uucp   {peora|ge-dab|uunet!tous}!bilver!alex
  34. ///__)     Internet:  alex@bilver.oau.org | alex%bilver@peora.sdc.ccur.com
  35.