Checking if an Integer is an Exact Binary Power

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Sat Apr 23 23:48:47 PDT 2016


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.
>
> 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.

Note that (A | B) & -(A | B) will give you the minimal power of 2 
that divide A and B.

Now, if A == B, you get (A & -A) == A to test if A is a power of 
2.


More information about the Digitalmars-d mailing list