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

前端 未结 12 2096
梦谈多话
梦谈多话 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:48

    According to me , the simplest way to get the zero bit count in a positive integer is the following piece of code.

    int get_zero_bit_count(int num)
    {
        int cnt = 0;
    
        while(num > 0)
            {
                int and_num = num & 1;
    
                if (and_num != num) cnt++;
    
                num >>= 1; 
            }
    
            return cnt;
        }
    

    This piece of code is easy to understand and is selp explainatory . This works well for positive integers.

提交回复
热议问题