Advertisement

How do i determine if a number if a power of 2?

Started by October 09, 2002 05:50 AM
6 comments, last by jonbell 22 years, 4 months ago
I need to know if a number if a power of 2 when i load a texture cause OpenGL doesn''t seem to support other texture sizes directly.
Over here (read the comments too)
Advertisement
The main function that the aboe link reffers to :

inline int LowestBitMask(int v)
{
return ((v & -v));
}

Surely &''ing a number with its negative equivilent ALWAYS returns the original. If this is right then none of it works.
My mistake i am a dumbass
You can also and the number with one minus it. I think.
"I don''t know with what weapons the third world war will be fought, but I know the fourth will be fought with sticks and stones." Einstein
For any 32-bit word, you can go through iterating through each bit and counting the number of bits. Once you realise there are more than 1 bits or if its not zero, then you know its not a power of 2 since binary is a base two numbering system.

bool check_power_of_two(unsigned int val32)
{
/* First check if its zero */
if (!val32) return false;

/* Count number of bits stopping if its more than 1 */
int n = 0, c = 0;
for (; n < 32; n++)
{
if (val32 & 1 << n) c++;
if (c >= 2) return false;
}

/* We have confirmed that there is 1 bit set */
return true;
}

There may be quicker ways, however this is the most certain and reliable way I know of at the moment.
Advertisement
I''ve always used div_t and the remainder to find out if anything is divisible by a specific number.

An example :
div_t div_test;
div_test = div(value,2);

if (div_test.rem != 0)
{
// is not divisible by 2
}
else
{
// is divisible by 2
}

Not sure whether this is more memory eating than the other options but its another choice to try..

Tina
That page also got:

  inline bool IsPow2(int v){   return (!(v & (v - 1)));}  
____________________________________MSN | AIM | YIM | ICQ

This topic is closed to new replies.

Advertisement