forked from vonj/snippets.org
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bitcnt_2.c
38 lines (30 loc) · 790 Bytes
/
bitcnt_2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
** Bit counter by Ratko Tomic
*/
#include "bitops.h"
int CDECL bitcount(long i)
{
i = ((i & 0xAAAAAAAAL) >> 1) + (i & 0x55555555L);
i = ((i & 0xCCCCCCCCL) >> 2) + (i & 0x33333333L);
i = ((i & 0xF0F0F0F0L) >> 4) + (i & 0x0F0F0F0FL);
i = ((i & 0xFF00FF00L) >> 8) + (i & 0x00FF00FFL);
i = ((i & 0xFFFF0000L) >> 16) + (i & 0x0000FFFFL);
return (int)i;
}
#ifdef TEST
#include <stdlib.h>
#include "snip_str.h" /* For plural_text() macro */
main(int argc, char *argv[])
{
long n;
while(--argc)
{
int i;
n = atol(*++argv);
i = bitcount(n);
printf("%ld contains %d bit%s set\n",
n, i, plural_text(i));
}
return 0;
}
#endif /* TEST */