Jump to content
  • Advertisement
Sign in to follow this  
AltecZZ

how to bit shift in C++?

This topic is 3927 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!