std.math.isPowerOf2

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Sat Oct 1 21:59:36 PDT 2016


On 10/1/2016 8:46 PM, Andrei Alexandrescu wrote:
> On 10/01/2016 11:05 PM, Manu via Digitalmars-d wrote:
>> Unsigned case is:
>>   return (x & -x) > (x - 1);
>>
>> Wouldn't this be better:
>>   return (sz & (sz-1)) == 0;
>>
>> I also don't understand the integer promotion and recursive call in
>> the integer case. Can someone explain how the std.math implementation
>> is ideal?
>
> The intent is to return 0 when the input is 0. Looking at
> https://github.com/dlang/phobos/blob/master/std/math.d, the implementation for
> signed integers might be simplified a bit. -- Andrei
>

Interestingly, this is one of the few algorithms that can be tested with an 
exhaustive test of all possibilities!


More information about the Digitalmars-d mailing list