home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / sys / mac / programm / 20804 < prev    next >
Encoding:
Internet Message Format  |  1993-01-06  |  1.7 KB

  1. Path: sparky!uunet!cs.utexas.edu!natinst.com!natinst.com!not-for-mail
  2. From: stepan@natinst.com (Stepan Riha)
  3. Newsgroups: comp.sys.mac.programmer
  4. Subject: Re: (Q) Need bit manipulation algorithm
  5. Date: 6 Jan 1993 10:57:45 -0600
  6. Organization: National Instruments, Austin, TX
  7. Lines: 33
  8. Message-ID: <1if329INN2f0@falcon.natinst.com>
  9. References: <1993Jan6.022430.19469@leland.Stanford.EDU> <1993Jan6.032113.597@planets.risc.rockwell.com> <20751@ucdavis.ucdavis.edu>
  10. NNTP-Posting-Host: falcon.natinst.com
  11.  
  12. In article <20751@ucdavis.ucdavis.edu> lim@toadflax.cs.ucdavis.edu (Lloyd Lim) writes:
  13. >In article <1993Jan6.032113.597@planets.risc.rockwell.com> sho@risc.rockwell.com (Sho Kuwamoto) writes:
  14. >>
  15. >>Maybe not the fastest method, but a simple one:
  16. >>   1) come up with an algorithm which counts the number of
  17. >>      1's in a given bit pattern.  You'll either use a loop
  18. >>      with shifts and increments in it, or you'll use masks.
  19. >>[...]
  20. >
  21. >There is a neat trick for counting the number of bits in a word that
  22. >a Microsoft geek showed me one time.  If there are k bits with 1's,
  23. >it runs in O(k) time.
  24. >...  Anyone remember this algorithm?
  25.  
  26. I've come up with another algorithm that's O(log(n)) where n is the number
  27. of bits.  For a 32 bit integer it takes 5 iterations.  It works by counting
  28. the number of ones in 2 adjacent bits, then 4 adjacent bits, then 8, etc.
  29.  
  30. long NumOnes(register unsigned long x)
  31. {
  32.     register int    i;
  33.     unsigned long masks[5] = {    0x55555555, 0x33333333, 0x0F0F0F0F,
  34.                     0x00FF00FF, 0x0000FFFF };
  35.     register unsigned long *mask = masks;
  36.     for (i=0; i<5; i++, mask++)
  37.         x = (x&*mask) + ((x>>(1<<i))&*mask);
  38.     return (long)x;
  39. }
  40.  
  41.     - Stepan
  42. -- 
  43.    Stepan Riha -- stepan@natinst.com
  44.  
  45.