且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何计算整数中的零位数?

更新时间:2021-07-05 05:44:55

最简单的最朴素的方法是迭代这些位并计数:

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;
}