+ -
当前位置:首页 → 问答吧 → 解释解释这个算法吧, 看的头晕

解释解释这个算法吧, 看的头晕

时间:2010-08-12

来源:互联网

  1. unsigned int hweight32(unsigned int w)
  2. {
  3.         unsigned int res = w - ((w >> 1) & 0x55555555);
  4.         res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
  5.         res = (res + (res >> 4)) & 0x0F0F0F0F;
  6.         res = res + (res >> 8);
  7.         return (res + (res >> 16)) & 0x000000FF;
  8. }


  9. #define BITMAP_LAST_WORD_MASK(nbits)                                        \
  10. (                                                                        \
  11.         ((nbits) % BITS_PER_LONG) ?                                        \
  12.                 (1UL<<((nbits) % BITS_PER_LONG))-1 : ~0UL                \
  13. )

  14. int __bitmap_weight(const unsigned long *bitmap, int bits)
  15. {
  16.         int k, w = 0, lim = bits/BITS_PER_LONG;

  17.         for (k = 0; k < lim; k++)
  18.                 w += hweight32(bitmap[k]);

  19.         if (bits % BITS_PER_LONG)
  20.                 w += hweight32(bitmap[k] & BITMAP_LAST_WORD_MASK(bits));

  21.         return w;
  22. }
复制代码
主要是 hweight32

作者: zylthinking   发布时间: 2010-08-12

统计w二进制表示中1的个数

作者: daybreakcx   发布时间: 2010-08-12

网上搜一下函数名就能找到很多结果,附上一个解释比较具体的:
http://blog.chinaunix.net/u1/44250/showart_1115776.html

作者: daybreakcx   发布时间: 2010-08-12