home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / BITCNT_1.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  804b  |  44 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 bit_count(long x)
  10. {
  11.         int n = 0;
  12. /*
  13. ** The loop will execute once for each bit of x set, this is in average
  14. ** twice as fast as the shift/test method.
  15. */
  16.         if (x) do
  17.               n++;
  18.         while (0 != (x = x&(x-1))) ;
  19.         return(n);
  20. }
  21.  
  22. #ifdef TEST
  23.  
  24. #include <stdlib.h>
  25. #include "snip_str.h"               /* For plural_text() macro    */
  26.  
  27. main(int argc, char *argv[])
  28. {
  29.       long n;
  30.  
  31.       while(--argc)
  32.       {
  33.             int i;
  34.  
  35.             n = atol(*++argv);
  36.             i = bit_count(n);
  37.             printf("%ld contains %d bit%s set\n",
  38.                   n, i, plural_text(i));
  39.       }
  40.       return 0;
  41. }
  42.  
  43. #endif /* TEST */
  44.