The first method is to use a normal loop:
Unsigned int getbitnum1 (unsigned int nvalue) <br/>{< br/> const unsigned int nnumofbitinbyte = 8; <br/> unsigned int tempmask = 1; <br/> unsigned int n = 0; <br/> for (unsigned int I = 0; I <sizeof (nvalue) * nnumofbitinbyte; I ++) <br/> {<br/> (0 <(nvalue & tempmask ))? N ++: 0; <br/> tempmask <= 1; <br/>}< br/> return N; <br/>}
Or
Unsigned int getbitnum2 (unsigned int nvalue) <br/>{< br/> const unsigned int nnumofbitinbyte = 8; <br/> unsigned int tempmask = 1; <br/> unsigned int n = 0; <br/> for (unsigned int I = 0; I <sizeof (nvalue) * nnumofbitinbyte; I ++) <br/> {<br/> (0 <(nvalue & tempmask ))? N ++: 0; <br/> nvalue >>= 1; <br/>}< br/> return N; <br/>}
The second method uses optimized Cycle Statistics:
Unsigned int getbitnum3 (unsigned int nvalue) <br/>{< br/> unsigned int n = 0; <br/> while (0 <nvalue) <br/> {// The <SPAN class = 'wp _ keywordlink '> Code </span> refers to a nvalue (in fact, the specific point is the first one counted from the low position. (1) <br/> // bit) and all subsequent bits become 0 <br/> nvalue & = (nvalue-1); <br/> N ++; <br/>}< br/> return N; <br/>}
In the third method, I never thought of it... for reference:
Unsigned int getbitnum4 (unsigned int nvalue) <br/>{< br/> nvalue = (0 xaaaaaaaa & nvalue)> 1) + (0x55555555 & nvalue ); <br/> nvalue = (0 xcccccccc & nvalue)> 2) + (0x33333333 & nvalue); <br/> nvalue = (0xf0f0f0 & nvalue)> 4) + (0x0f0f0f & nvalue); <br/> nvalue = (0xff00ff00 & nvalue)> 8) + (0x00ff00ff & nvalue ); <br/> nvalue = (0xffff0000 & nvalue)> 16) + (0x0000ffff & nvalue); </P> <p> return nvalue; <br/>}< br/>
References: http://www.cppblog.com/OnTheWay2008/archive/2010/03/29/110467.html