How many digits of 1 in the binary representation of an unsigned Int?

Source: Internet
Author: User

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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.