Checking if an Integer is an Exact Binary Power
Shachar Shemesh via Digitalmars-d
digitalmars-d at puremagic.com
Mon Apr 25 08:35:44 PDT 2016
On 23/04/16 16:04, Nordlöw wrote:
> Wanted: CT-trait and run-time predicate for checking whether its single
> integer parameter is an exact power of two.
>
> I guess
>
> https://dlang.org/phobos/std_math.html#.truncPow2
>
> or
>
> https://dlang.org/phobos/std_math.html#.nextPow2
>
> could be reused, but I bet there's a more efficient way of checking this.
The standard way (assuming 2's complement machine) is:
if( i == (-i & (~i)) )
writeln("Power of 2");
Works for all 2's complement integers except 0, where it gives a false
positive.
Shachar
More information about the Digitalmars-d
mailing list