c - How to count 1 in a int variable -


this question has answer here:

if have int = 15; know 0x00 00 00 0f in binary 0000 0000 0000 0000 0000 0000 0000 1111 has 4 1 in binary.

i want count sum of 1 in int variable.

i write this:

int count1(int i) {     int j = 0,num = 0;     for(;j<32;j++)         if((i<<j )&0x80000000)             num++;     return num; } 

it can work, think slow,i mean maybe have millions int data. dose 1 have more effective way this?

int main()  {       int number = 15;      int sum; // total bits set in number     (sum = 0; number; sum++)     {       number &= number - 1;      }     cout<<sum<<endl; }  

Comments

Popular posts from this blog

java - How to Configure JAXRS and Spring With Annotations -

visual studio - TFS will not accept changes I've made to a Java project -

php - Create image in codeigniter on the fly -