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
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.