SourceComment: I am back ;-) and algorithm for PowerOf2

Dear all,

static bool isPowerOf2 (quint32 size)
{
while ((size & 0×01) == 0)
size >>= 1;
return size == 1;
}
A faster version could be

static bool isPowerOf2 (quint32 size)
{
if( size == 0 ) return false;
return ( (size & size-1) == 0 );
}

A very long time back, I remember Brian Kernighan, in comp.lang.c, gave his favourite bit counting algorithm…

int count = 0;
for (; i; i &= i-1)
++count;
The above version is derived from this one ;-)

– cheerio atul

Would you like to post a relpy?


This post starts a thread.
Follow-ups:
Re: SourceComment: I am back ;-) and algorithm for PowerOf2
Atul, that's a really nice trick :-). Pushed in your public branch! Regards, Peter