How do i determine if a number if a power of 2?
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.
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.
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.
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
October 13, 2002 07:20 AM
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.
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.
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
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
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement