home *** CD-ROM | disk | FTP | other *** search
/ Media Share 13 / mediashare_13.zip / mediashare_13 / ZIPPED / PROGRAM / SNIP9404.ZIP / BITCNT_1.C < prev    next >
C/C++ Source or Header  |  1994-04-03  |  727b  |  42 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 (0 != (x = x&(x-1)))
  15.               ;
  16.         return(n);
  17. }
  18.  
  19. #ifdef TEST
  20.  
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23.  
  24. #define plural_text(n) &"s"[(1 == (n))]
  25.  
  26. void main(int argc, char *argv[])
  27. {
  28.       long n;
  29.  
  30.       while(--argc)
  31.       {
  32.             int i;
  33.  
  34.             n = atol(*++argv);
  35.             i = bit_count(n);
  36.             printf("%ld contains %d bit%s set\n",
  37.                   n, i, plural_text(i));
  38.       }
  39. }
  40.  
  41. #endif /* TEST */
  42.