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

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

    Kernighan way of counting set bits

    unsigned int v; // count the number of bits set in v
    unsigned int c; // c accumulates the total bits set in v
    for (c = 0; v; c++)
    {
      v &= v - 1; // clear the least significant bit set
    }
    

    Can be easily adapted for the task given. A number of iterations here is equal to a number of bits set.

    I also recommend the link above for various other ways of solving this and others types of bit-related tasks. There also is a single line example of obtaining bit count implemented in macros.

提交回复
热议问题