Possible Duplicates:
Query about working out whether number is a power of 2
What does this function do?
n & (n-1) – where can this expression be used ?
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.
It’s figuring out if
nis either 0 or an exact power of two.It works because a binary power of two is of the form
1000...000and subtracting one will give you111...111. Then, when you AND those together, you get zero, such as with:Any non-power-of-two input value (other than zero) will not give you zero when you perform that operation.
For example, let’s try all the 4-bit combinations:
You can see that only
0and the powers of two (1,2,4and8) result in a0000/falsebit pattern, all others are non-zero ortrue.