Checking if an Integer is an Exact Binary Power

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Sat Apr 23 10:28:21 PDT 2016


On 04/23/2016 11:29 AM, Andrei Alexandrescu wrote:
> On 4/23/16 10:41 AM, Dmitry Olshansky wrote:
>> On 23-Apr-2016 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.
>>
>> x & (x-1) == 0
>
> Yah, that's the canonical. I forgot why I chose (x & -x) > (x - 1) over
> it. -- Andrei

Oh I remember. If x == 0, the result should also be 0. -- Andrei



More information about the Digitalmars-d mailing list