开发者

How to count the number of ones in a byte without a loop in c? [duplicate]

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

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;
}


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

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


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).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜