一个字节中二进位1的个数
两个相似的方法,一个右移所查看的字节;一个查看左移1.
#include <stdio.h> int getOneBits(unsigned char num) { int count = 0; for(int i = 0; i < 8; i++) { if((num & (1 << i)) != 0) count++; } return count; } int main(void) { printf("%d\n", getOneBits((unsigned char)10)); return 0; }
#include <stdio.h> int getOneBits(unsigned char num) { int count = 0; for(int i = 0; i < 8; i++) { if(((num>>i) & 1) != 0) count++; } return count; } int main(void) { printf("%d\n", getOneBits((unsigned char)10)); return 0; }
在网上看到有查表法,效率高,貌似比较麻烦:
//将0x00~0xFF对应存在二进位0的个数保存在unsigned int C[256]中 const int C[256]={8,7,7,6,7,6,6,5,7,……,1,0}; //然后 int ZeroBitsCount(BYTE b) {return C[(unsigned int)b];}
时间: 2024-10-18 18:47:53