问题描述
我已经经历此等问题约32位,但对于64位数字阅读?如果我只是掩盖了上下4个字节,在32位进行计数,然后添加在一起?
I have read through this SO question about 32-bits, but what about 64-bit numbers? Should I just mask the upper and lower 4 bytes, perform the count on the 32-bits and then add them together?
推荐答案
您可以找到64位版本在这里http://en.wikipedia.org/wiki/Hamming_weight
You can find 64 bit version here http://en.wikipedia.org/wiki/Hamming_weight
有这样的事情
long NumberOfSetBits(long i)
{
i = i - ((i >> 1) & 0x5555555555555555);
i = (i & 0x3333333333333333) + ((i >> 2) & 0x3333333333333333);
return (((i + (i >> 4)) & 0xF0F0F0F0F0F0F0F) * 0x101010101010101) >> 56;
}
这是一个64位版本的code形式在这里 http://stackoverflow.com/questions/109023
This is a 64 bit version of the code form here http://stackoverflow.com/questions/109023
使用约书亚的建议,我将它改造成这样的:
Using Joshua's suggestion I would transform it into this:
int NumberOfSetBits(ulong i)
{
i = i - ((i >> 1) & 0x5555555555555555UL);
i = (i & 0x3333333333333333UL) + ((i >> 2) & 0x3333333333333333UL);
return (int)(unchecked(((i + (i >> 4)) & 0xF0F0F0F0F0F0F0FUL) * 0x101010101010101UL) >> 56);
}
修改:我发现了一个bug,而测试的32位版本。我补充缺少括号。总和应当按位&安培之前完成;,在最后一行
EDIT: I found a bug while testing 32 bit version. I added missing parentheses. The sum should be done before bitwise &, in the last line
EDIT2 作为ULONG增加更安全的版本
EDIT2 Added safer version for ulong
这篇关于伯爵在64位(长,大的)整数位的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!