Saturday, December 5, 2009

C code to check if an integer is a power of 2 or not in a single line

Method1


if(!(num & (num - 1)) && num)
{
  // Power of 2!
}



Method2


if(((~i+1)&i)==i)
{
 //Power of 2!
}


Method 3 
if (x && !(x & (x-1)) == 0)

or

(a-1) xor a == 0


No comments:

Post a Comment