0 is not a power of 2

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu May 21 06:25:03 PDT 2015


On 5/19/15 7:41 PM, deadalnix wrote:
> On Tuesday, 19 May 2015 at 22:43:46 UTC, Steven Schveighoffer wrote:
>> On 5/19/15 5:32 PM, deadalnix wrote:
>>> On Tuesday, 19 May 2015 at 20:09:23 UTC, Steven Schveighoffer wrote:
>>>> On 5/19/15 4:01 PM, deadalnix wrote:
>>>>> Have you tried things like :
>>>>>
>>>>> (x >> bsr(x)) == 1 ?
>>>>>
>>>>> I have no idea if this is faster or not, but worth trying.
>>>>
>>>> Hm.. I think this would always succeed. Perhaps you mean:
>>>>
>>>> 1 << bsr(x) == x;
>>>>
>>>
>>> Both work as long as you use a fully defined instruction, like tzcnt.
>>
>> Hm... I messed up, (x >> bsr(x)) is always zero. I think you meant to
>> write:
>>
>> x >> (bsr(x) - 1)
>>
>> which always is 1.
>>
>> Either way, it doesn't work.
>>
>
> No.
>
> bsr(1) is 0.
> 1 >> bsr(1) is 1.

Gah, I messed up, used output from old code that wasn't doing what I 
thought it was. You are right about that.

But my whole point there was that x >> bsr(x) is ALWAYS 1.

2 >> bsr(2) == 1
3 >> bsr(3) == 1
4 >> bsr(4) == 1
17 >> bsr(17) == 1

So really, your test checks to see if a value is zero or not, not 
whether it's a power of 2.

BUT, the opposite mechanism would work:

1 << bsr(x) == x;

> 0 >> anything is 0.

Hah, good point :) Even if bsr(0) is undefined it doesn't matter. Didn't 
think of that.

But that means the opposite solution I mentioned above, doesn't work, 
still back to square one.

-Steve


More information about the Digitalmars-d mailing list