【发布时间】:2020-01-09 23:02:57
【问题描述】:
我看到这个代码叫做"Counting bits set, Brian Kernighan's way"。我很困惑如何“按位与”整数及其减量来计算设置位,有人可以解释一下吗?
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
}
【问题讨论】:
-
您是否尝试过用笔和纸逐步完成该过程,看看会发生什么?
标签: c bit-manipulation kernighan-and-ritchie