当我需要在 Int64 上应用汉明权重算法来计算设置位时,我想问一下 BitMask 的样子。
对于 Int32,它看起来像这样:
public int HammingWeight(int value)
{
value = value - ((value >> 1) & 0x55555555);
value = (value & 0x33333333) + ((value >> 2) & 0x33333333);
return (((value + (value >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
然而,由于 Int32 只有 4 个字节长,所以 Int64 是 8 个字节长。
因此,相同的位掩码不适用于 Int64。
对 Int64 值使用汉明权重算法的正确位掩码是什么?
编辑:检查@just.ru提供的链接后,我使用了这个解决方案:
/// <summary>
/// Count the set bits in a ulong using 24 arithmetic operations (shift, add, and)..
/// </summary>
/// <param name="x">The ulong of which we like to count the set bits.</param>
/// <returns>Amount of set bits.</returns>
private static int HammingWeight(ulong x)
{
x = (x & 0x5555555555555555) + ((x >> 1) & 0x5555555555555555); //put count of each 2 bits into those 2 bits
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333); //put count of each 4 bits into those 4 bits
x = (x & 0x0f0f0f0f0f0f0f0f) + ((x >> 4) & 0x0f0f0f0f0f0f0f0f); //put count of each 8 bits into those 8 bits
x = (x & 0x00ff00ff00ff00ff) + ((x >> 8) & 0x00ff00ff00ff00ff); //put count of each 16 bits into those 16 bits
x = (x & 0x0000ffff0000ffff) + ((x >> 16) & 0x0000ffff0000ffff); //put count of each 32 bits into those 32 bits
x = (x & 0x00000000ffffffff) + ((x >> 32) & 0x00000000ffffffff); //put count of each 64 bits into those 64 bits
return (int)x;
}