计算位数的3种方法

方法1:
int count_bits(unsigned int data) {
  
int cnt=0;
  
  
while(data!=0{
    data
=data&(data-1);
    cnt
++;
  }

  
return cnt;
}



方法2:(为一个字节打表)
static unsigned char byte_bit_count[256];

void initialize_count_bits() {
  
int cnt,i,data;
  
for(i=0;i<256;i++{
    cnt
=0;
    data
=i;
    
while(data!=0{
      data
=data&(data-1);
      cnt
++;
    }

    byte_bit_count[i]
=cnt;
  }

}


int count_bits(unsigned int data)
{
  
const unsigned char *byte=(unsigned char*)&data;
  
return byte_bit_count[byte[0]]+byte_bit_count[byte[1]]+
           byte_bit_count[
byte[2]]+byte_bit_count[byte[3]];
}


方法3:(计算一个字种所有位(0,1)的和)
int count_bits(unsigned int x)
{
  
static unsigned int mask[]={0x55555555,
                                           
0x33333333,
                                           
0x0F0F0F0F,
                                           
0x00FF00FF,
                                           
0x0000FFFF}
;
  
int i;
  
int shift;

  
for(i=0,shift=1;i<5;i++,shift*=2)
    x
=(x&mask[i])+((x>>shift)&mask[i]);
  
return x;
}




posted on 2008-02-29 12:34  woodfish  阅读(882)  评论(1编辑  收藏  举报

导航