4

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

Hello,

Is there a more compact way of counting the number of ones in a byte without using a loop? I don't want to do the following if I don't have to. Thanks.

char myValue = 0x0F;
int counter = 0;
while (myValue > 0)
{
 if (myValue & 0x01)
 {
 counter ++;
 }
 myValue = myValue >> 1;
}
asked Jan 26, 2011 at 15:28
6
  • 5
    Possible duplicate of stackoverflow.com/questions/109023/… Commented Jan 26, 2011 at 15:29
  • Are you asking for a solution in C? C++? objective-c? These are all very different languages. The solution is going to be slightly different for each one. Commented Jan 26, 2011 at 15:31
  • @wheaties: I'm pretty sure C and C++ don't differ here. Commented Jan 26, 2011 at 15:33
  • @vitaut: not a duplicate question, but there's definitely a duplicate answer. Commented Jan 26, 2011 at 15:35
  • 2
    @Paul Nathan in C++ I'd just put it into a std::bitset and then call the bitset::count function. In C, that doesn't exist. Commented Jan 26, 2011 at 15:36

2 Answers 2

8
 ((i>>3)&1)+((i>>2)&1)+((i>>1)&1)+(i&1)

Or use assembly (SSE/MMX). http://gurmeet.net/puzzles/fast-bit-counting-routines/

answered Jan 26, 2011 at 15:31
Sign up to request clarification or add additional context in comments.

1 Comment

Your code is a sum of four brackets, each bracket can be either 0 or 1. So the result can be at most four, but there can be 8 ones in a Byte.
0

This works if you initialize the table correctly.

static const unsigned char one_bits_in_byte[] = { 0, 1, 1, 2, 1, ... };
int counter = one_bits_in_byte[myValue & 0xFF];

Of course, you'd write a program with a loop in it to generate the table so that your final program doesn't have a loop in it. If you are feeling cost conscious, you can encode just the data for 0..15 and process the two halves (nybbles) of the value with shifts. But with 24 GB of physical memory, this is unlikely to be a major problem. And you could also simply compute the value on demand with masking operations, etc (like VGE suggests, but extended to a whole byte).

answered Jan 26, 2011 at 15:39

2 Comments

If you're going to be cost-conscious, presumably it won't be about your 2/4GB of physical memory, it will be about your L1 cache. RAM is just L4 cache for the page file anyway ;-)
@Steve: +1 your "L4" comment made me laugh! :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.