0 is not a power of 2

Johan Engelen via Digitalmars-d digitalmars-d at puremagic.com
Tue May 19 09:26:26 PDT 2015


On Tuesday, 19 May 2015 at 05:51:27 UTC, Andrei Alexandrescu 
wrote:
> On 5/18/15 10:37 PM, H. S. Teoh via Digitalmars-d wrote:
>> On Mon, May 18, 2015 at 10:16:47PM -0700, Andrei Alexandrescu 
>> via Digitalmars-d wrote:
>> [...]
>>> bool isPowerOf2(uint x)
>>> {
>>>     return (x & (x - 1) | !x) == 0;
>>> }
>> [...]
>>
>> Are you sure that's correct? Doesn't that return true for all 
>> non-zero
>> numbers?
>
> Excerpt from std.experimental.allocator.common:
>
> package bool isPowerOf2(uint x)
> {
>     return (x & (x - 1) | !x) == 0;
> }
>
> unittest
> {
>     assert(!isPowerOf2(0));
>     assert(isPowerOf2(1));
>     assert(isPowerOf2(2));
>     assert(!isPowerOf2(3));
>     assert(isPowerOf2(4));
>     assert(!isPowerOf2(5));
>     assert(!isPowerOf2(6));
>     assert(!isPowerOf2(7));
>     assert(isPowerOf2(8));
>     assert(!isPowerOf2(9));
>     assert(!isPowerOf2(10));
> }

I wish we had something like clang's -Wparenthesis.
I think
     return ( (x & (x-1)) | !x ) == 0;
is much clearer here.

  -Johan


More information about the Digitalmars-d mailing list