How does this code work to Find the next highest power of 2 for any given number [>1] for 32 bit integer?
n--;
n = n | n>>1;
n = n | n>>2;
n = n | n>>4;
n = n | n>>8;
n = n | n>>16;
n++;
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 sequence of shifts and bitwise-ors guarantees a number that consists of all
1s, which is one less than a power-of-2. Adding 1 to it gives a power-of-2.The initial decrement by 1 is to make it work for values of
nthat are already powers-of-2.(Obviously, this code doesn’t work if
nis originally0.)