[PATCH 07/14] Cleanup: avoid undefined shift operation

Jef Driesen jef at libdivecomputer.org
Wed Jan 3 07:23:43 PST 2018


On 29-12-17 08:00, Linus Torvalds wrote:
> On Thu, Dec 28, 2017 at 4:35 PM, Dirk Hohndel <dirk at hohndel.org> wrote:
>> 
>>          unsigned int signbit = (1 << (n - 1));
>> -       unsigned int mask = (0xFFFFFFFF << n);
>> +       unsigned int mask;
>> +
>> +       // shifting a 32bit constant by more than 31 bits has 
>> undefined behavior
>> +       if (n == 32)
>> +               mask = 0;
>> +       else
>> +               mask = (0xFFFFFFFF << n);
> 
> Ugh. That's ugly.
> 
> It's much simpler to just do
> 
>          unsigned int mask = ~(signbit-1);
> 
> instead.
> 
> Yes, that mask ends up including the sign bit (the old mask did not),
> but that doesn't matter for the end result.

That's indeed an easier and nicer fix!

The bitwise not can even be omitted from the mask, and moved to the 
return statements (where there is already both a mask and a ~mask).

Jef


More information about the devel mailing list