かつてJR横浜線 十日市場駅近くのMebius (CPU:Pentium 150MHz)より発信していたウェブログです。 32bitの立っているビット数を高速に数えるアルゴリズムとして、 int bitcount(unsigned long n) { n = ((n&0xaaaaaaaa) >> 1) + (n&0x55555555); n = ((n&0xcccccccc) >> 2) + (n&0x33333333); n = ((n&0xf0f0f0f0) >> 4) + (n&0x0f0f0f0f); n = ((n&0xff00ff00) >> 8) + (n&0x00ff00ff); n = ((n&0xffff0000) >> 16) + (n&0x0000ffff); return n; } こういうのが良く知られている。1行目で2ビットずつ足し合わせることで2ビットの中の
![ビット数を数えるルーチン - Weblog on mebius.tokaichiba.jp](https://cdn-ak-scissors.b.st-hatena.com/image/square/eaea4f1ab483b3a5c040320219c637342892ba2c/height=288;version=1;width=512/http%3A%2F%2Fynomura.dip.jp%2Fmt-static%2Fsupport%2Ftheme_static%2Frainier%2Fimg%2Fsiteicon-sample.png)