Count the number of bits that are "on" in a byte

Possible Duplicates:
Count the number of set bits in an integer
Best algorithm to count the number of set bits in a 32-bit integer?

That's an exam question and that is all I have - "Count the number of bits that are "on" in a byte" "On" means 1, I assume. Do I need to create a BitArray, randomly populate it and then iterate through it or is there a different way?


使用BitArray可能是有效的,但你也可以

byte b = ... ;

int count = Convert.ToString(b,2).ToCharArray().Count(c => c=='1');

Is this a interview question?

For a byte the fastest way would be to pre-compute an array such that a[i] = number of bits in i - the memory overhead is negligible.

链接地址: http://www.djcxy.com/p/72590.html

上一篇: 以更快的方式找出变量中没有设置的位

下一篇: 计算一个字节中“开”的位数