对于一个字(32bit)的数据,求其中“1”的个数,要求算法的执行效率尽可能地高。
方法一:
- #define TESTBYTE (0x3200)
-
-
int main(int argc, char* argv[])
-
{
-
int i;
-
int count = 0;
-
-
for (i=0; i<32; i++)
-
{
-
if (TESTBYTE & (0x01 << i)) //这里其实可以这样做
if ((TESTBYTE >> i) & 0x01)
-
{
-
count++;
-
}
-
}
-
-
printf("%d\n", count);
-
return 0;
-
}
方法二:这个方法和uCOS里面任务调度那部分的算法有点相似,将他的可能性全部罗列出来,并用数组来定义,但是这样的情况仅仅局限于bit位数比较低的情况,如8位,如果高达16位,那么就将有65535种情况,也不大合适。
这里仅仅是举bit位数为8的情况。
- unsigned char numTable[256] =
-
{
-
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3,
-
3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3,
-
4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4,
-
3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3,
-
4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6,
-
6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4,
-
5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
-
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3,
-
4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4,
-
4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6,
-
7, 6, 7, 7, 8
-
};
阅读(1772) | 评论(0) | 转发(0) |