home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / s / snip1292.zip / BITCNT_1.C < prev    next >
C/C++ Source or Header  |  1991-09-23  |  704b  |  41 lines

  1. /*
  2. **  Bit counter by Ratko Tomic
  3. */
  4.  
  5. int bit_count(long x)
  6. {
  7.         int n = 0;
  8. /*
  9. ** The loop will execute once for each bit of x set, this is in average
  10. ** twice as fast as the shift/test method.
  11. */
  12.         if (x) do
  13.               n++;
  14.         while (x = x&(x-1));
  15.         return(n);
  16. }
  17.  
  18. #ifdef TEST
  19.  
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22.  
  23. #define plural_text(n) &"s"[(1 == (n))]
  24.  
  25. void main(int argc, char *argv[])
  26. {
  27.       long n;
  28.  
  29.       while(--argc)
  30.       {
  31.             int i;
  32.  
  33.             n = atol(*++argv);
  34.             i = bit_count(n);
  35.             printf("%ld contains %d bit%s set\n",
  36.                   n, i, plural_text(i));
  37.       }
  38. }
  39.  
  40. #endif /* TEST */
  41.