Checking if an Integer is an Exact Binary Power
Andrei Alexandrescu via Digitalmars-d
digitalmars-d at puremagic.com
Sun Apr 24 22:35:12 PDT 2016
On 4/24/16 9:17 PM, Xinok wrote:
> I modified David's solution a bit to (hopefully) eliminate the branch:
> bool powerOf2(uint x){ return !x ^ !(x & (x - 1)); }
>
> 0000000000000000 <_D4test8powerOf2FkZb>:
> 0: 50 push %rax
> 1: 53 push %rbx
> 2: 48 89 fa mov %rdi,%rdx
> 5: 85 d2 test %edx,%edx
> 7: 0f 94 c0 sete %al
> a: 8d 8a ff ff ff ff lea -0x1(%rdx),%ecx
> 10: 85 ca test %ecx,%edx
> 12: 0f 94 c3 sete %bl
> 15: 32 c3 xor %bl,%al
> 17: 5b pop %rbx
> 18: 59 pop %rcx
> 19: c3 retq
> 1a: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1)
>
> The branches are gone but I'm really not sure if this is better or worse.
With gdc https://godbolt.org/g/jcU4np isPow2B is the winner (shortest
code, simplest instructions). -- Andrei
More information about the Digitalmars-d
mailing list