Search code examples
cbit-manipulationbit-shiftbinary-operatorsnot-operator

Why does this bitwise shift-right appear not to work?


Could someone explain to me why the mask is not shifted to the right at all? You can use anything in place of that 1 and the result will be the same.

unsigned mask = ~0 >> 1;
printf("%u\n", mask);

Solution

  • It's a type issue. If you cast the 0 to unsigned it'll be fine:

    unsigned mask = ~ (unsigned) 0 >> 1;
    printf("%u\n", mask);
    

    Edit per comments: or use unsigned literal notation, which is much more succinct. :)

    unsigned mask = ~0u >> 1;
    printf("%u\n", mask);