How to count the number of ones in a byte without a loop in c?
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).
链接地址: http://www.djcxy.com/p/72594.html上一篇: 计数位数最快的方法
下一篇: 如何计算c中没有循环的字节数?