What is the most efficient way to count the number of bits which are set in a value?

Showing Answers 1 - 9 of 9 Answers

Santosh

  • Jul 20th, 2005
 

shifting each bit left till the no of bits end

  Was this answer useful?  Yes

Paresh

  • Sep 6th, 2005
 

foo(unsigned char *ByteField) 

int i=0,j=0; 
unsigned char *BytePos; 
short Bit; 
 
BytePos = ByteField + sizeof(ByteField); 
 
for (i=0; i
if (*(BytePos - i) > (char ) 0) 

for (j=0; j<8; j++) 

 
if (((*(BytePos - i)) & 1<
Bit = (i * 8) + j; 
printf("Bit Set %d n",Bit); 





 
Should give u the bit which are set

  Was this answer useful?  Yes

Raks

  • Oct 21st, 2005
 

#define ISBIT(pos,val) ((1<<(pos-1))&val)


void main(void)
{
 int i=0x00;
 int cnt=0;
 int pos=0;
 for(pos=1;pos<=(sizeof(i)*8);pos++)
 {
  if(ISBIT(pos,i))
  {
   cnt++;
  }
 }

 printf("Count %d",cnt);
}

  Was this answer useful?  Yes

prakash

  • Jan 27th, 2006
 

int cnt_bits(int num) {

   int cnt = 0;

   while(num) {

       if(num % 2) cnt++;

       num /= 2;

   }

   return cnt;

}

  Was this answer useful?  Yes

ptusha

  • Aug 17th, 2006
 

int fnCountbits(int num )
{
 int iCount = 0;
 while ( num )
 {
   num &= (num-1) ;
  iCount++;
 } 

return iCount;

}

Visitor

  • Aug 23rd, 2006
 

Real smart solution to this question is to use a LookUp table.

  Was this answer useful?  Yes

As part of SSE4 instruction set available in Intel and AMD there is one instruction named POPCNT to count number of bits set to 1.
 
Furthermore, you can use it in gcc through the builtins __builtin_popcount [and ...countl and ...countll depending on the size of the argument] if you enable -msse4.2 
 
int __builtin_popcount (unsigned int)
Generates the popcntl machine instruction. 
 
int __builtin_popcountl (unsigned long)
Generates the popcntl or popcntq machine instruction, depending on the size of unsigned long. 
 
int __builtin_popcountll (unsigned long long)
Generates the popcntq machine instruction.

  Was this answer useful?  Yes

grvmab

  • Oct 2nd, 2010
 

#include<stdio.h>
void main()
{
int n,r,c=0;
clrscr();
printf("Enter number:");
scanf("%d",&n);
while(n>0)
{
r=n%10;
c++;
n=n/10;
}
printf("nNumber of bits:%d",c);
getch();
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions