C语言--计算二进制数中1的个数(&)

//15
//00001111>>1
//00000111

int count_bit(unsigned int value)
{
int one = 0;
while(value)
{
if(value%2 == 1)
one++;
value = value >> 1;
}
return one;
}
//x&1;  n += x &1; x>>=1;
	  
//1111  & 0001 = 0001    n=1
//0111  & 0001 = 0001      2
//0011  & 0001 = 0001      3
//0001  & 0001 = 0001      4
int count_bit1(unsigned int x)
{ 
	int n=0;
  do  
  { 
	  n += x &1;
	  x>>=1; 
  }
  while (x!=0);
  return (n);
}

//x&(x-1)
//1111  & 1110 = 1110
//1110  & 1101 = 1100
//1100  & 1011 = 1000
//1000  & 0111 = 0000
int count_bit2(unsigned int value)
{
int count = 0;
while(value)
{
count++;
value = value & (value-1);
}
return count;
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。