home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / BITCNT_2.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  872b  |  41 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4. **  Bit counter by Ratko Tomic
  5. */
  6.  
  7. #include "bitops.h"
  8.  
  9. int CDECL bitcount(long i)
  10. {
  11.       i = ((i & 0xAAAAAAAAL) >>  1) + (i & 0x55555555L);
  12.       i = ((i & 0xCCCCCCCCL) >>  2) + (i & 0x33333333L);
  13.       i = ((i & 0xF0F0F0F0L) >>  4) + (i & 0x0F0F0F0FL);
  14.       i = ((i & 0xFF00FF00L) >>  8) + (i & 0x00FF00FFL);
  15.       i = ((i & 0xFFFF0000L) >> 16) + (i & 0x0000FFFFL);
  16.       return (int)i;
  17. }
  18.  
  19. #ifdef TEST
  20.  
  21. #include <stdlib.h>
  22. #include "snip_str.h"               /* For plural_text() macro    */
  23.  
  24. main(int argc, char *argv[])
  25. {
  26.       long n;
  27.  
  28.       while(--argc)
  29.       {
  30.             int i;
  31.  
  32.             n = atol(*++argv);
  33.             i = bitcount(n);
  34.             printf("%ld contains %d bit%s set\n",
  35.                   n, i, plural_text(i));
  36.       }
  37.       return 0;
  38. }
  39.  
  40. #endif /* TEST */
  41.