Count bits used in int

后端 未结 11 1465
梦谈多话
梦谈多话 2020-12-30 15:54

If you have the binary number 10110 how can I get it to return 5? e.g a number that tells how many bits are used? There are some likewise examples listed below:

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 16:38

    int CountBits(uint value)
    {
        for (byte i = 32; i > 0; i--)
        {
            var b = (uint)1 << (i - 1);
            if ((value & b) == b)
                return i;
        }
        return 0;
    }
    

提交回复
热议问题