Use BitOperations in more callsites (CoreCLR) by grant-d · Pull Request #22630 · dotnet/coreclr (original) (raw)

    [Fact]
    public static void Foo()
    {
        for (int i = 0; i < 32; i++)
        {
            uint n = 11u << i; // 0x1011, to make it more interesting

            int expected = BitOps.PopCount(n); // new
            int actual = bitcount(n); // old
            Assert.Equal(expected, actual);

            expected = BitOps.TrailingZeroCount(n); // new
            actual = bitindex(n); // old
            Assert.Equal(expected, actual);
        }
    }

    // Original source

    static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
    private static int bitcount(uint n)
    {
        int count = 0;
        for (; n != 0; n = n >> 4)
            count += nibblebits[n & 0x0f];
        return count;
    }
    private static int bitindex(uint n)
    {
        //Debug.Assert(bitcount(n) == 1);
        int idx = 0;
        while ((n & (1 << idx)) == 0)
            idx++;
        return idx;
    }