首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请教怎么计算一个字节中存在着多少个二进位0

2013-07-09 
请问如何计算一个字节中存在着多少个二进位0?如题请问如何计算一个字节中存在着多少个二进位0?[解决办法]/

请问如何计算一个字节中存在着多少个二进位0?
如题
请问如何计算一个字节中存在着多少个二进位0?
[解决办法]


//抱歉都是计算1的
//1)直接计算
int countByte(unsigned char x){
     x = (x & 0x55) +((x>>1)&0x55
     x = (x& 0x33) +(( x>>2)&0x33);
     return (x& 0x0F) +((x>>4)&0xF);   
}
//2)查表
int countHalfByte(unsigned char x){
   //       0  1   2  3  4  5  6  7 
   return "\x0\x1\x1\x2\x1\x2\x2\x3"[x];
}
int CountByte(unsigned char x){
   return countHalfByte[x &0x0f] +countHalfByte[(x>>4) &0x0f];
}
//3)循环
int CountByte(unsigned char x){
   int bits=0; 
   while(x){
       bits += (x & 1);// 或者if(x & 1) bits++;
       x >>= 1;
    }
   return bits;
}

//这都是计算1的,下面计算0的个数。

int CountByteZero(unsigned char x){
return sizeof(x) -CountByte(x);
}

热点排行