Count bits used in int

后端 未结 11 1467
梦谈多话
梦谈多话 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

    Be careful what you ask for. One very fast technique is to do a table lookup:

    int bittable [] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, ... };
    int numbits (int v)
    {
        return bittable [v];
    }
    

    where bittable contains an entry for every int. Of course that has complications for negative values. A more practical way would be to count the bits in bitfields of the number

    int bittable [16] = {0, 1, 1, 2,  1, 2, 2, 3,  1, 2, 2, 3,  2, 3, 3, 4};
    int numbits (int v)
    {
        int s = 0;
        while (v != 0)
        {
             s += bittable [v & 15];
             v >>= 4;
        }
        return s;
    }
    

提交回复
热议问题