De Bruijn algorithm binary digit count 64bits C#

前端 未结 4 2310
陌清茗
陌清茗 2021-01-04 21:26

Im using the \"De Bruijn\" Algorithm to discover the number of digits in binary that a big number (up to 64bits) has.

For example:

  • 1022 has 10 digits i
4条回答
  •  猫巷女王i
    2021-01-04 22:02

    After perusing various bit-twiddling info, this is how I'd do it... don't know how this stacks up next to DeBruijn, but should be considerably faster than using powers.

    ulong NumBits64(ulong x)
    {
        return (Ones64(Msb64(x) - 1ul) + 1ul);
    }
    
    ulong Msb64(ulong x)
    {  
        //http://aggregate.org/MAGIC/
        x |= (x >> 1);
        x |= (x >> 2);
        x |= (x >> 4);
        x |= (x >> 8);
        x |= (x >> 16);
        x |= (x >> 32);
        return(x & ~(x >> 1));
    }
    
    ulong Ones64(ulong x)
    {
        //https://chessprogramming.wikispaces.com/SIMD+and+SWAR+Techniques
        const ulong k1 = 0x5555555555555555ul;
        const ulong k2 = 0x3333333333333333ul;
        const ulong k4 = 0x0f0f0f0f0f0f0f0ful;
        x = x - ((x >> 1) & k1);
        x = (x & k2) + ((x >> 2) & k2);
        x = (x + (x >> 4)) & k4;
        x = (x * 0x0101010101010101ul) >> 56;
        return x;
    }
    

提交回复
热议问题