<分区>
重复:
Best algorithm to count the number of set bits in a 32-bit integer?
假设您有一个数字。有没有什么方法可以不使用迭代来计算该数字的二进制表示中等于 1 的位?我的意思是,有什么方法可以使用一些按位运算符和掩码在固定时间内完成。我需要适用于 32 位和 64 位架构的解决方案。差点忘了,C语言需要,汇编也不错。
<分区>
Best algorithm to count the number of set bits in a 32-bit integer?
假设您有一个数字。有没有什么方法可以不使用迭代来计算该数字的二进制表示中等于 1 的位?我的意思是,有什么方法可以使用一些按位运算符和掩码在固定时间内完成。我需要适用于 32 位和 64 位架构的解决方案。差点忘了,C语言需要,汇编也不错。
最佳答案
在http://graphics.stanford.edu/~seander/bithacks.html处有一个没有循环的比特计数算法. http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/ 中的大量位计数算法
关于计算数字中的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/843737/