0 is not a power of 2

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Thu May 21 13:46:37 PDT 2015


On Thursday, 21 May 2015 at 13:24:57 UTC, Steven Schveighoffer 
wrote:
> 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;
>

Ha yes. You'd want to use TZCNT.

Alternatively, with bsf on could do:

x << bsf(x) == 1 << [32|64]

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

Well no, there all needed to make it work :) Still no idea if 
this is actually faster, but there is one less operation to 
perform.


More information about the Digitalmars-d mailing list