Checking if an Integer is an Exact Binary Power

Nordlöw via Digitalmars-d digitalmars-d at puremagic.com
Sat Apr 23 06:39:19 PDT 2016


On Saturday, 23 April 2016 at 13:06:58 UTC, Vladimir Panteleev 
wrote:
> On Saturday, 23 April 2016 at 13:04:00 UTC, Nordlöw wrote:
>> Wanted: CT-trait and run-time predicate for checking whether 
>> its single integer parameter is an exact power of two.
>
> popcnt(x) <= 1 ?

Great.

My solution:

/** Check if `x` is an exact (binary) power of 2.
    TODO Move to std.math.
    */
bool isPow2(T)(T x)
     if (isIntegral!T)
{
     import core.bitop : popcnt;
     return popcnt(x) == 1;
}

@safe pure nothrow @nogc unittest
{
     // run-time
     assert(!7.isPow2);
     assert(8.isPow2);
     assert(!9.isPow2);

     // compile-time
     static assert(!7.isPow2);
     static assert(8.isPow2);
     static assert(!9.isPow2);
}

Destroy.


More information about the Digitalmars-d mailing list