# how to bit shift in C++?

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

## 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 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 on other sites
Quote:
 Original post by NitageIncidentally, 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.

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633735
• Total Posts
3013592
×