Error on negating unsigned types

Guillaume Chatelet via Digitalmars-d digitalmars-d at puremagic.com
Tue Jul 11 14:34:37 PDT 2017


On Tuesday, 11 July 2017 at 20:05:43 UTC, Johan Engelen wrote:
> On Tuesday, 11 July 2017 at 20:02:07 UTC, Johan Engelen wrote:
>> On Tuesday, 11 July 2017 at 19:57:06 UTC, Johan Engelen wrote:
>>> On Tuesday, 11 July 2017 at 19:46:00 UTC, Johan Engelen wrote:
>>>> [...]
>>>
>>> Also this nice hackery would need a workaround:
>>> ```
>>>    if ((y&(-y))==y)
>>> ```
>>
>> http://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/
>>
>> "The two’s complement of x is computed with ~x + 1, which 
>> inverts the bits of x and adds 1 (~x + 1 is equivalent to -x, 
>> but negation is technically illegal for an unsigned integer)."
>
> Codegen is the same for both: https://godbolt.org/g/JiHiEe
> So Phobos's `if ((y&(-y))==y)` can be rewritten to `if 
> ((y&(~y+1))==y)` without consequence.

Interestingly returning a bool saves one register and a XOR.


More information about the Digitalmars-d mailing list