You're viewing a comment by Phil and its responses.

Phil Permalink
January 10, 2017, 20:51

Still looking for efficient ways to:
1. Count how many bits set to 1
2. Find the left-most 1.

I recently learned this clever test for whether x is a power of 2:
(x & (x-1))==0

Comment Responses

cyanide Permalink
January 18, 2017, 00:19

About counting 1-bits. The artical shows how to clear rightmost 1-bit. This way you do a loop untill you get zero:
int count = 0; while(x!-=0) {count++; x&=x-1;}

Nathan Myers Permalink
May 11, 2018, 05:11

You use the POPCNT instruction. Compilers have an intrinsic, __popcount(i). In C++, std::bitset


(i).count() compiles to a single POPCNT instruction.

Reply To This Comment

(why do I need your e-mail?)

(Your twitter handle, if you have one.)

Type the word "antispam_143": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.