Search code examples
cshift

Can someone explain the behavior of my right-shift in C?


I don't understand the outcome of the following code:

unsigned char p = 170;
p = (~p) >> 4 & 255;

The Result is: 245 and I don't understand why.

First the (~p) will applied what makes 10101010 to 01010101

This is a positive number so >> 4 would lead to 00000101 in my understanding.

But it seems to be 11110101 and I don't understand why. In my understanding shifting a positive number to the right will insert 0 and not 1.


Solution

  • When used in an expression, an integer narrower than int is generally converted to an int. So, using 16-bit int for illustration, in (~p) >> 4 & 255:

    • p is 101010102.
    • This is converted to an int, producing 00000000101010102.
    • ~p produces 11111111010101012.
    • (~p) >> 4 may produce 11111111111101012. (Right-shift of negative values is implementation-defined.)
    • (~p) >> 4 & 255 produces 111101012.
    • 111101012 is 245.