2

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?

asked Mar 21, 2011 at 19:33
2

2 Answers 2

7

Using BitArray might be efficient but you could also do

byte b = ... ;
int count = Convert.ToString(b,2).ToCharArray().Count(c => c=='1');
answered Mar 21, 2011 at 19:38
Sign up to request clarification or add additional context in comments.

2 Comments

I think that is called a lambda expression, right? BtW, sorry I can not upvote, I am not registered yet.
yes c => c == '1' is a lambda expression predicate.
0

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.

answered Mar 21, 2011 at 19:42

2 Comments

Unless it's for an embedded system. Then, doing it by the nibble is a better tradeoff.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.