#### Archived

This topic is now archived and is closed to further replies.

# How do I ..?

This topic is 6927 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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

##### Share on other sites
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

##### Share on other sites
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

##### Share on other sites
on a side note, you can do this:

return exponet == testnum;

instead of the if, else block

##### Share on other sites
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.

GA

Edited by - ga on 5/2/00 3:13:31 PM

##### Share on other sites
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

• 16
• 9
• 15
• 10
• 13