How would i go about finding the number of ‘zero’ bits in C++.
Suppose I have an integer;
int value = 276;
For which I have the bits 100010100, but how do I count the zeros?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The easiest most naive way is to just iterate over the bits and count:
There are all number of better (for different values of “better”) ways, but this is quite clear, very terse (code-wise), and doesn’t require a bunch of setup.
One micro-optimization that might be considered an improvement is to not compute the mask to test each bit, instead shift the value and always test the rightmost bit: