Checking if an Integer is an Exact Binary Power

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Tue Apr 26 13:48:19 PDT 2016


On 26.04.2016 17:27, Xinok wrote:
> On Monday, 25 April 2016 at 15:35:14 UTC, Dominikus Dittes Scherkl wrote:
>> On Monday, 25 April 2016 at 15:27:02 UTC, Xinok wrote:
>>> Brute force.
>>>
>>> http://dpaste.dzfl.pl/882d7cdc5f74
>> Yeah. And your test spares the failed case int.min (0x80000000),
>> because in this case x & -x is negative, but of cause x>>>1 is
>> positive, so it returns false despite -(2^^31) is in fact a power of
>> two. So this requires an extra cast to work correct (in fact no big
>> difference in the assembly):
>>
>> return (Unsigned!T)(x & -x) > (Unsigned!T)(x >>> 1);
>
> How is it wrong? Negative numbers are NOT powers of two (unless you have
> an imaginary/complex exponent), so it's still correct to return false
> for -int.min. Should it not?
>
> http://www.wolframalpha.com/input/?i=solve+2^n+%3D+-%282^31%29+for+n

static assert(2^^31==int.min); // :o)


More information about the Digitalmars-d mailing list