🎉 Celebrating 25 Years of GameDev.net! 🎉
Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!
How do I determine if an integer is a power of two?
If you want only to deal with integers, you can also just check that there is one and only one bit set in the entire number (in which case it must be a power of two).
bool powerOfTwo (unsigned int number){if (number == 0) return false;unsigned int numberOfbits = 0;unsigned int bitmask = 1;for (i=0; i< sizeof (unsigned int); i++){ //Check if current bit is set with logical and if (bitmask & number) numberOfBits++; //If more than one bit is set, this is not a power of two if (numberOfBits > 1) return false; //Get Ready to check the next bit bitmask <<= 1;}return true;}
invective has a little error: you must multiply the result of sizeof() by CHAR_BIT to obtain bits instead of bytes.
bool isPowerOfTwo(unsigned int number){ bool found = false; unsigned int mask = 1; for (int i = 0; i < (sizeof(number) * CHAR_BIT); ++i) { if (number & mask) if (found) return false; else found = true; mask <<= 1; } return found;}
Beer Hunter, that''s pretty slick
.
[Resist Windows XP''s Invasive Production Activation Technology!]
![](wink.gif)
[Resist Windows XP''s Invasive Production Activation Technology!]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement