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;}
alexk7
if((number & (number - 1)) == 0)
You don''t need to over-complicate this, guys
You don''t need to over-complicate this, guys
Beer Hunter, that''s pretty slick .
[Resist Windows XP''s Invasive Production Activation Technology!]
[Resist Windows XP''s Invasive Production Activation Technology!]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement