How do I count the number of zero bits in an integer?

前端 未结 12 2090
梦谈多话
梦谈多话 2021-02-02 00:25

How would i go about finding the number of \'zero\' bits in C++. Suppose I have an integer;

int value = 276; 

For which I have the bits 100010

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-02 00:38

    The easiest most naive way is to just iterate over the bits and count:

    size_t num_zeroes = 0;
    
    for(size_t i = 0; i < CHAR_BIT * sizeof value; ++i)
    {
      if ((value & (1 << i)) == 0)
        ++num_zeroes;
    }
    

    There are all number of better (for different values of "better") ways, but this is quite clear, very terse (code-wise), and doesn't require a bunch of setup.

    One micro-optimization that might be considered an improvement is to not compute the mask to test each bit, instead shift the value and always test the rightmost bit:

    for(size_t i = 0; i < CHAR_BIT * sizeof value; ++i, value >>= 1)
    {
      if ((value & 1) == 0)
        ++num_zeroes;
    }
    

提交回复
热议问题