相关疑难解决方法(0)

数字中设置的位数

以下是一个神奇的公式,它给出了一个数字中设置的位数(汉明重量).

/*Code to Calculate count of set bits in a number*/
int c;
int v = 7;
v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
printf(" Number of Bits is %d",c);
/*-----------------------------------*/
Run Code Online (Sandbox Code Playgroud)

来自:http: //graphics.stanford.edu/~seander/bithacks.html

有谁能解释一下这背后的理由?

c c++ bit-manipulation bitmap bit

16
推荐指数
1
解决办法
3625
查看次数

标签 统计

bit ×1

bit-manipulation ×1

bitmap ×1

c ×1

c++ ×1