计算偶数边界处配对未设置位的数量
给定一个 64 位数字,找出偶数边界处配对未设置位的数量的最佳方法是什么。 MSB 之后的额外零填充应被忽略。
例如:
对于两个数字 25223 和 10578,
25223 -- 01 10 00 10 10 00 01 11
7 6 5 4 3 2 1 0
Count = 2, (at positions 2 and 5)
10578 -- 00 10 10 01 01 01 00 10
7 6 5 4 3 2 1 0
Count = 1, (at position 1. Ignore position 7)
我可以做一个掩码,移 2 并进行比较,但我正在寻找更好的东西。还有比这更快的吗:
def PairedCount(n):
c=0
while(n!=0):
if((n & 3) == 0):
c+=1
n >>= 2;
return c
如果我想计算偶数边界处配对非零位的数量怎么办?最好的方法是什么?
Given a 64-bit number what's the best way to find out the number of paired un-set bits at even boundaries. The extra zero padding after the MSB should be ignored.
For example:
For the two numbers 25223 and 10578
25223 -- 01 10 00 10 10 00 01 11
7 6 5 4 3 2 1 0
Count = 2, (at positions 2 and 5)
10578 -- 00 10 10 01 01 01 00 10
7 6 5 4 3 2 1 0
Count = 1, (at position 1. Ignore position 7)
I could do a mask, shift-by-2 and compare, but I'm looking for something better. Is there anything faster than this:
def PairedCount(n):
c=0
while(n!=0):
if((n & 3) == 0):
c+=1
n >>= 2;
return c
What if I want to count the number of paired non-zero bits at even boundaries? What's the best method for that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个简单的问题,但你提出的方式让我感到害怕:)
让我们首先尝试对 32 位的
1
进行处理(你会明白为什么):我们现在需要它
count_set_bits(unsigned)
,这是众所周知的函数:http: //www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable要计算零位,请使用
count_pairs(~n)
或编辑:刚刚观察了备注Given 64 位数字...MSB 之后的额外零填充应被忽略。在什么MSB之后?你的意思是输入是一个字节?或词?
It's a simple question, but the way you put it scares me :)
Let's first try doing it to pairs of
1
s (you'll see why) for 32 bits:All we need now it
count_set_bits(unsigned)
, that is very known function: http://www-graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTableTo count zero bits use
count_pairs(~n)
orEDIT: just observed the remark Given the 64 bit number... The extra zero padding after the MSB should be ignored. After what MSB? Do you mean the input is a byte? or word?
根据@rusliks 的回答,我尝试让我的答案简短一些。
based on @rusliks answer, I tried making my answer a bit short.
这是针对 32 位的.. 0x55555555 是一个依赖项.. 是设置位的数量顺序
This is for 32bits .. 0x55555555 is a dependency .. is order of number of set bit
这并没有便宜多少(每对零一个循环+开销),但它只是暴露一些小技巧。
This is not much cheaper (one loop per pair of zeroes + overhead) but it's just to expose a few bit tricks.