我發現下面的代碼來計算給定整數的二進制表示中1-bits
的數量。任何人都可以解釋它如何工作?而且這些口罩是如何選擇的?謝謝。該代碼如何工作來計算1位的數量?
int count_one(int x)
{
x = (x & (0x55555555)) + ((x >> 1) & (0x55555555));
x = (x & (0x33333333)) + ((x >> 2) & (0x33333333));
x = (x & (0x0f0f0f0f)) + ((x >> 4) & (0x0f0f0f0f));
x = (x & (0x00ff00ff)) + ((x >> 8) & (0x00ff00ff));
x = (x & (0x0000ffff)) + ((x >> 16) & (0x0000ffff));
return x;
}
這是作業嗎? – Femaref
請參閱http://graphics.stanford.edu/~seander/bithacks.html,搜索「並行計數位設置」。 – paxdiablo
@Femaref不,不是。只是想弄清楚它是如何工作的。 – herohuyongtao