1 | // Compile with : g++ a.c -o a ; ./a |
---|
2 | |
---|
3 | #include <stdio.h> |
---|
4 | #include <stdlib.h> |
---|
5 | |
---|
6 | int popcount(); |
---|
7 | int popcountl(); |
---|
8 | |
---|
9 | __attribute__ ((target ("default"))) |
---|
10 | inline int popcountl(unsigned long i){ |
---|
11 | if (sizeof(int) == 4){ |
---|
12 | // Returns the number of '1' bits in a 32-bits integer. |
---|
13 | i = i - ((i >> 1) & 0x55555555); |
---|
14 | i = (i & 0x33333333) + ((i >> 2) & 0x33333333); |
---|
15 | return( ((i + (i >> 4) & 0x0F0F0F0F) * 0x01010101) >> 24 ); |
---|
16 | } |
---|
17 | else{ |
---|
18 | // Returns the number of '1' bits in a 64-bits integer. |
---|
19 | i = i - ((i >> 1) & 0x5555555555555555ULL); |
---|
20 | i = (i & 0x3333333333333333ULL) + ((i >> 2) & 0x3333333333333333ULL); |
---|
21 | return( ( ((i + (i >> 4)) & 0x0f0f0f0f0f0f0f0fULL) * 0x0101010101010101ULL ) >> 56 ); |
---|
22 | } |
---|
23 | } |
---|
24 | |
---|
25 | __attribute__ ((target ("default"))) |
---|
26 | inline int popcount(unsigned int i){ |
---|
27 | return popcount((unsigned long) i); |
---|
28 | } |
---|
29 | |
---|
30 | __attribute__ ((target ("popcnt"))) |
---|
31 | inline int popcount(unsigned int i){ |
---|
32 | return __builtin_popcount(i); |
---|
33 | } |
---|
34 | __attribute__ ((target ("popcnt"))) |
---|
35 | inline int popcountl(unsigned long i){ |
---|
36 | return __builtin_popcountl(i); |
---|
37 | } |
---|
38 | |
---|
39 | int main(int argc, char ** argv){ |
---|
40 | long n=atoi(argv[1]); |
---|
41 | printf("%d\n",popcountl(n)); |
---|
42 | } |
---|