0 is not a power of 2
Atila Neves via Digitalmars-d
digitalmars-d at puremagic.com
Tue May 19 00:56:26 PDT 2015
Aren't predictable branches cheap on current architectures?
Atila
On Tuesday, 19 May 2015 at 05:16:48 UTC, Andrei Alexandrescu
wrote:
> So there's this classic trick:
>
> bool isPowerOf2(uint x)
> {
> return (x & (x - 1)) == 0;
> }
>
> Pretty neat, but it wrongly returns true for x == 0. So the
> obvious fix is:
>
> bool isPowerOf2(uint x)
> {
> return x && (x & (x - 1)) == 0;
> }
>
> But that has branches in it. So I came up with:
>
> bool isPowerOf2(uint x)
> {
> return (x & (x - 1) | !x) == 0;
> }
>
> which has no branches at least with dmd, see
> http://goo.gl/TVkCwc.
>
> Any ideas for faster code?
>
>
> Thanks,
>
> Andrei
More information about the Digitalmars-d
mailing list