On Sunday, 24 April 2016 at 21:45:32 UTC, Walter Bright wrote:
On 4/24/2016 8:33 AM, Andrei Alexandrescu wrote:
On 04/24/2016 02:57 AM, deadalnix wrote:
On Saturday, 23 April 2016 at 15:29:08 UTC, Andrei
Alexandrescu wrote:
Yah, that's the canonical. I forgot why I chose (x & -x) >
(x - 1)
over it.
I'm not sure why do you test against x - 1 when you could
test for
equality. Not only it looks like it is going to require an
extra
computation (x - 1) but also it doesn't work for 0.
So if you do (x & -x) == x that returns 1 for x == 0. For many
applications you
want to yield 0. So you test for (x & -x) > (x - 1) such that
for x == 0 the
right hand side is a large number. -- Andrei
This sort of stuff should go on wiki.dlang.org page!
Please no cmp.
Just
bool isPowerOf2(uint x) { return x && !(x & (x - 1)); }