Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_2.9_bitcount2s.c
1240 views
1
/* In twos complement number systems, x &= (x-1) deletes the rightmost 1 bit in x.
2
* Explain why? Use this to right a faster version of bitcount. Bitcount program counts
3
* the number of 1 bits in the integer */
4
5
#include<stdio.h>
6
7
int bitcount(unsigned x);
8
9
int main(void)
10
{
11
printf("%d",bitcount((unsigned)12));
12
}
13
14
int bitcount(unsigned x)
15
{
16
int b;
17
18
for(b=0; x!=0; x &= x-1)
19
++b;
20
21
return b;
22
}
23
24