如何计算整数中的零位数? [英] How do I count the number of zero bits in an integer?
问题描述
我如何去找到C ++中的零位数。
假设我有一个整数;
How would i go about finding the number of 'zero' bits in C++. Suppose I have an integer;
int value = 276;
我有100010100位,但是如何计算零?
For which I have the bits 100010100, but how do I count the zeros?
推荐答案
最简单的最朴素的方法是迭代这些位并计数:
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;
}
这篇关于如何计算整数中的零位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!