使用 C 计算 8 位二进制数中的设置位数
我有一个长度为 8 的二进制数,例如 00110101
有 8 位设置。
我需要快速位计数来确定设置位的数量,即 popcount 又名人口计数。 像这样运行算法 x=x&(x-1)
会将其限制为数字包含的设置位数,但我不太确定如何使用它。
与 计算设置位数不同在 32 位整数中,我只有 8 位整数,因此 O(log width) bithack 方法仍然有几个步骤,可能不会比 O(set_bits) 或 4 位或CPU 上的 8 位查找表没有硬件 popcount,或者以无法接受假设支持的方式进行编译。
I have got a binary number of length 8 for eg 00110101
There are 8 bits set.
I need a fast bit count to determine the number of set bits, the popcount aka population count.
Running the algo like this x=x&(x-1)
will limit it to the number of set bits in the number contains but I am not very sure as to how to use it.
Unlike Count the number of set bits in a 32-bit integer, I only have 8-bit integers, so O(log width) bithack methods still have several steps and might not be better than O(set_bits) or 4-bit or 8-bit lookup tables on CPUs without hardware popcount, or if compiling in a way that can't take assume support.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
此
x=x&(x-1)
从二进制字符串中删除最低设置位。如果计算在数字变为 0 之前删除最低位的次数,您将得到已设置的位数。This
x=x&(x-1)
removes the lowest set bit from the binary string. If you count the number of times you remove the lowest bit before the number becomes 0, you'll get the number of bits that were set.执行 x = x & (x-1) 将删除最低位集。因此,在您的情况下,迭代将执行为,
允许的迭代次数将是给定数字中的总位数。
doing
x = x & (x-1)
will remove the lowest bit set. So in your case the iterations will be performed as,The number of iterations allowed will be the total number of bits in the given number.
美国专利 6,516,330 – 计算数据字中的设置位
(我只是发明了它 - 不要不要让我解释。)
US Patent 6,516,330 – Counting set bits in data words
(I only invented it -- don't ask me to explain it.)
问题中描述的方法(通常归因于 K&R )的复杂度为 n,其中 n 是数字中设置的位数。
通过使用额外的内存,我们可以将其变为 O(1):
使用位数(编译时操作)初始化查找表,然后引用它;
您可以在这里找到该方法:计数由查找表设置的位数
您可以找到Henry S. Warren, Jr.(2007)“The Quest for an Accelerated Population Count”中对不同方法的详细讨论,美丽的代码 pp.147-158奥莱利
The method described in the question (generally ascribed to K&R ) has the complexity of n, where n is the number of bits set in the number.
By using extra memory we can bring this to O(1):
Initialize a lookup table with the number of bit counts (compile-time operation) and then refer to it;
You can find the method here : Counting bits set by lookup table
You can find a detailed discussion of different methods in Henry S. Warren, Jr.(2007) "The Quest for an Accelerated Population Count", Beautiful Code pp.147-158 O'Reilly
我的代码片段仅适用于无符号整数:
希望这有帮助。
I have this code snippet works with unsigned integer only:
Hope this helps.
根据您计算设置位的方式 - 在我们的例子中,实际设置位的数量为 4;位宽(我在此将其定义为最高位组的数字加 1)为 6(因为您需要 6 位来表示您的数字)。后一个可以通过
(未经测试)确定
Depending on how you count the set bits - the number of really set bits are 4 in our case; the bit-width (which I hereby define as the number of the highest bit set plus 1) is 6 (as you need 6 bits to represent your number). The latter one can be determined with
(untested)
摘自matrix67的博客,是中文的。
Taken from matrix67's blog, which is in Chinese.