2012-02-16 6 views
1

可能性の重複:設定されたビットの数を見つける方法
Best algorithm to count the number of set bits in a 32-bit integer?
Counting the number of bits that are set数(設定されたビットの数と同じ回数を繰り返すことができます)

(3ビットが設定されている場合は、ループを3回しか反復できません)

符号なし整数でループを反復することができます。
+0

[?ベストアルゴリズムは32ビット整数に設定されたビットの数をカウントする] [1] [1]:http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer/5469563#5469563 –

答えて

6

この0は、私がこれを行うための知っている方法であり、それだけでvのビット数を保持する実行cの終わりに、vに設定されたビット数のために反復されます:

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プログラミング言語第2版(ブライアンW.カーニハンとデニスM.リッチーによる)

例:

v = 1010; //2 bits are set 
v - 1 = 1010(10 decimal) - 1 = 1001(9 decimal) 

1010 
1001 & 
------ 
1000   The least significant bit is unset, c is incremented by 1 

v = 1000 
v - 1 = 1000 - 1 = 0111 

1000 
0111 & 
------- 
0000   The least significant bit is unset again, c is incremented 
      by 1, the loop stops because there are no more set bits. 
関連する問題