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

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

    Do a one's compliment then count the 1s.

    count_zero_bits( x ) = count_one_bits( ~x );

    Implement the code to count the ones.

    template< typename I > 
    int count_one_bits( I i )
    {
       size_t numbits = 0;
       for( ; i != 0; i >>= 1 )
       {
          numbits += i&1;
       }
    }
    

    although there is an issue with my function if i is a negative number because >> will put 1 bits into the right hand side so you will get a never-terminating loop. If there is a templated way to enforce an unsigned type that would be ideal.

    Once you have that then:

    template< typename I > int count_zero_bits( I i )
    {
       return count_one_bits( ~i );
    }
    

    will work.

提交回复
热议问题