用Hamming weight统计二进制中1的个数的实现原理

修电视的攻城狮 2010-10-06 09:12:40

在网上找到一种据说是性能最好的统计二进制中1的个数方法,用的是Hamming weight,实现如下:

/* ===========================================================================
* Problem:
* The fastest way to count how many 1s in a 32-bits integer.
*
* Algorithm:
* The problem equals to calculate the Hamming weight of a 32-bits integer,
* or the Hamming distance between a 32-bits integer and 0. In binary cases,
* it is also called the population count, or popcount.[1]
*
* The best solution known are based on adding counts in a tree pattern
* (divide and conquer). Due to space limit, here is an example for a
* 8-bits binary number A=01101100:[1]
* | Expression | Binary | Decimal | Comment |
* | A | 01101100 | | the original number |
* | B = A & 01010101 | 01000100 | 1,0,1,0 | every other bit from A |
* | C = (A>>1) & 01010101 | 00010100 | 0,1,1,0 | remaining bits from A |
* | D = B + C | 01011000 | 1,1,2,0 | # of 1s in each 2-bit of A |
* | E = D & 00110011 | 00010000 | 1,0 | every other count from D |
* | F = (D>>2) & 00110011 | 00010010 | 1,2 | remaining counts from D |
* | G = E + F | 00100010 | 2,2 | # of 1s in each 4-bit of A |
* | H = G & 00001111 | 00000010 | 2 | every other count from G |
* | I = (G>>4) & 00001111 | 00000010 | 2 | remaining counts from G |
* | J = H + I | 00000100 | 4 | No. of 1s in A |
* Hence A have 4 1s.
*
* [1] http://en.wikipedia.org/wiki/Hamming_weight
*
* ===========================================================================
*/
请问下,这个方法的原理是什么?为什么经过上面求A、B、C、D、E、F、G、H、I、J就得出了结果?

...全文
152 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
showjim 2010-10-06
  • 打赏
  • 举报
回复
Intel SSE4有专用指令POPCNT
这个算法的改良版第一次归并用的是减法,比直接两两归并少一两条指令
  • 打赏
  • 举报
回复
就是归并来计算求和,先是1bit和1bit的和存入2bit里,然后2bit和2bit的和存入4bit里,然后4bit和4bit的和存入8bit里。而在每个阶段,求和以后结果的范围都不会超越那几个bit的最大值。

移位的作用就是为了相临的bits相加时对齐用的。

33,007

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧