Sign in to follow this  

how to bit shift in C++?

This topic is 3741 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi everyone, I'm a bit new to C++, I'm trying to write a function that will check if an integer is a power of 2. The quickest way to do this is probably to use bit-shifting, and count the number of 1's. However, I'm not sure how to do this in C/C++... bool IsPowerOf2(int i) { int count = 0; while (i < 0) { int bit = // ?? How to shift i? if (bit == 1) count++; if (count > 1) return false; } return true; }

Share this post


Link to post
Share on other sites
Incidentally, you don't need to bit shift to find if a number is a power of 2.


bool IsPowerOf2(unsigned int i)
{
return !(i & (i - 1)) && i;
}



I also changed your input to be unsigned. Your original function returns true for any negative input - is that what you wanted?

Share this post


Link to post
Share on other sites
Quote:
Original post by Nitage
Incidentally, you don't need to bit shift to find if a number is a power of 2.

*** Source Snippet Removed ***

I also changed your input to be unsigned. Your original function returns true for any negative input - is that what you wanted?


You are right, I missed that!

Thanks a lot, I never thought you could do it that way.

Share this post


Link to post
Share on other sites

This topic is 3741 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this