2^???

2 views
Skip to first unread message

Johann Obermayr

unread,
Oct 23, 2007, 8:44:46 AM10/23/07
to
Hallo,

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

Andreas Heyer

unread,
Oct 23, 2007, 9:06:42 AM10/23/07
to
"Johann Obermayr" <Johann....@sigmatek.at> wrote in message
news:OvCxJJXF...@TK2MSFTNGP05.phx.gbl...

> Gibt es da was schelleres ?

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

Volker Enderlein

unread,
Oct 23, 2007, 9:08:52 AM10/23/07
to
Hallo Jimmy,

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

Martin Richter [MVP]

unread,
Oct 23, 2007, 9:21:18 AM10/23/07
to
Hallo Volker!

> 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

Reply all
Reply to author
Forward
0 new messages