Advertisement

How do I determine if an integer is a power of two?

Started by December 24, 2001 12:34 AM
5 comments, last by joshh 22 years, 11 months ago
How do I determine if an integer is a power of two? josh
if (pow(2, log(2, number)) == number)
blah;


ought to work
Advertisement
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
Thanks for all the replies, it is exactly what i needed to know.

joshh
if((number & (number - 1)) == 0)

You don''t need to over-complicate this, guys
Advertisement
Beer Hunter, that''s pretty slick .

[Resist Windows XP''s Invasive Production Activation Technology!]

This topic is closed to new replies.

Advertisement