Suche eine schnelle funktion, um festzustellen,
ob ein integer ein wert von 2^. ist. (1, 2, 4, 8, 16, 32, 64, ...)
meine lösung ist
unsigned int iTest = 16384;
bool IsExp2(unsigned int iTest)
{
unsigned int i = 1;
for( int j = 0; j < 32; j++)
{
if (i == iTest)
return true;
i >>= 1;
}
return false;
}
Gibt es da was schelleres ?
Danke
Jimmy
Loop unrolling oder switch-Statement? Sind doch nur 32 Werte zu prüfen.
Die Vergleiche machst du ja auch in deiner Schleife, ersparst dir aber
die Bitrödelei.
Wenn du dir den Carnaugh-Plan dieses logischen Problems mal vorstellst,
erhalte ich den Eindruck, dass man nichts zusammenfassen kann, also
keine kürzere Verknüpfung als
y= x1&!x2&!x3... | !x1&x2&!x3... | !x1&!x2&x3... | ...
finden kann, wobei x1...xn die Bits des Eingabewertes darstellen.
MfG
Andreas
On Tue, 23 Oct 2007 14:44:46 +0200, Johann Obermayr
<Johann....@sigmatek.at> wrote:
> Gibt es da was schelleres ?
>
> Danke
> Jimmy
schau mal bei Wikipedia rein.
http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_number_is_a_power_of_two
Zitat:
The binary representation of integers makes it possible to apply a very
fast test to determine whether a given integer x is a power of two:
x is a power of two <==> (x & (x - 1)) equals zero.
Ciao Volker
--
Volker Enderlein
> The binary representation of integers makes it possible to apply a very
> fast test to determine whether a given integer x is a power of two:
> x is a power of two <==> (x & (x - 1)) equals zero.
Geil! :-)
--
Martin Richter [MVP] WWJD http://blog.m-ri.de
"A well-written program is its own heaven; a poorly written
program is its own hell!" The Tao of Programming
FAQ: http://www.mpdvc.de Samples: http://www.codeproject.com