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

Linus Torvalds torvalds at linux-foundation.org
Thu Dec 28 23:00:06 PST 2017


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.

              Linus


More information about the devel mailing list