开发者

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

This question already has answers here: Closed 11 years ago.

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?


Using BitArray might be efficient but you could also do

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜