When I was digging into OpenGL texture mapping, I was checking with some sample code (I’m not remembering from where I downloaded that), inside the code, I found a simple line to check whether the texture dimensions are power of two or not. If the texture is non power of two, the program had to check whether the graphics hardware is capable of supporting non-power of two textures or not by querying GL_ARB_texture_non_power_of_two string. Actually, I was much attracted with the single line of code which is checking the power of two using binary operators. It’s might be a simple logic for the programmers who deals with bits and bytes. But still it’s intresting. The sample code author had particularly mentioned the logic was adopted from SJ Baker’s Cool Code List.
Here’s baker’s method (??) for checking whether a number is exact power of two or not.
b = ((n&(n-1))==0) ;
(NB: This code sets ‘b’ to TRUE if ‘n’ is an integer power of two – in this context, both zero and one are considered to be powers of two.)
This code actually works by changing the least significant ’1′ bit of ‘n’ to a ’0′. If ‘n’ is a power of two, it only has one ’1′ bit – and zeroing it leaves you with zero as the answer. Hence, the inner expression is also a cute trick…
If we would make it as a simple function it may appears as follows.
bool IsPowerOfTwo( int n )
{
// Function returns true if the number if power of two
return ((n&(n-1))==0) ;
}
The logic is simply straight forward which can be interpreted by using Windows Calculator. J Check it yourself. The link contains some other cool tips as well.
Sidebar: Bakers also shared his interesting “Cruel Code List” as well J

This code also work in the same way
return (value & -value) == value;
Zero is not a power of two, nor are negative numbers. Since n is an int, it could be 0) && (n&(n-1))==0);
See my article http://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/ . Specifically, the sections “9. Decrement and Compare” and “How NOT to Check”
Rick Regan
Somehow my comment got cut off. It’s supposed to say “Since n is an int, it could be less than or equal to 0″. You need to add a check for this.
Find if the given number is a power of 2.
//include math.h
void main()
{
int n,logval,powval;
printf(“Enter a number to find whether it is s power of 2\n”);
scanf(“%d”,&n);
logval=log(n)/log(2);
powval=pow(2,logval);
if(powval==n)
printf(“The number is a power of 2″);
else
printf(“The number is not a power of 2″);
getch();
}