Skip to main content
GameDev.net gamedev.net
🔒 Locked

How do I ..?

Started by drago Apr 29, 2000 at 3:28 PM 4 replies 750+ views
Original Post
drago
drago
How can I check a float if it isn''t an integer? What i want to do is check if a float is a power of 2:
bool IsPowerOf2(unsigned int nInput)
{
   float fPower = log10(nInput) / log10(2);

   // Check if fPower is an integer
   ???????????????????????????????????

}
 
or is this impossible due to round-off errors? ---------- Drago
osu!
WitchLord
WitchLord
I would make the test like this:

float fPower = log10(nInput) / log10(2);
float fRound = (float)floor(fPower+0.5f);
if( (float)fabs(fPower - fRound) < 1e-5f )
{
// The number is power of two
}

You could also count the number of set bits in nInput. If there are only one bit set then you know nInput is power of two. If this is faster or not I don''t know.

- WitchLord
AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - <a href="http://www.angelcode.com/tower" rel
UraniumRod
UraniumRod
My funcion would look like this.

bool ispower2(int num)
{
float exponet = log10(num) / log10(2);
int testnum;

testnum = (int)exponet;
if(exponet == testnum) {
// then its a power of two
return true;
}

return false;
}

hope that helps


Edited by - UraniumRod on 4/29/00 6:29:33 PM
------------------------------"My sword is like a menacing cloud, but instead of rain, blood will pour in its path." - Sehabeddin, Turkish Military Commander 1438.
adammil
adammil
on a side note, you can do this:

return exponet == testnum;

instead of the if, else block


adamm@san.rr.com
adamm@san.rr.com
ga
ga

bool IsPowerOf2(unsigned int nInput)
{
unsigned char bitcounter = 0;
for(unsigned char i=0;(i<32) && (bitcounter<2);i++)
{
bitcounter += nInput&1;
nInput >>= 1;
}
return (bitcounter==1);
}


If you want to test if an integer is a power of 2, you don't need to work with floating point operations.

Visit our homepage: www.rarebyte.de.st

GA

Edited by - ga on 5/2/00 3:13:31 PM
Visit our homepage: www.rarebyte.de.stGA
drago
drago
Could you explain me that code? I think I''m gonna read me a good C++ book and finish it for a change ;-)..

----------
Drago, VerSoft
osu!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.