Search code examples
cunsignedsignedbit-shift

Why the output is always -1?


This is the code:

char x=-1>>2;
printf("%d",x);

Even if i do x = -N>>2 it will give 1 only.

x = -1 => 11111111 
x= -1>>2 ==> 00111111 = 3F ??

Also even if I do int x = -1>>2 the output will be 1.

Could you explain how this calculation is carried out?


Solution

  • I believe your code will work if you use

    unsigned char x=-1>>2;
    

    For signed numbers (including characters), right shift does not append zeroes. This is called sign bit extension. C uses 2's complement form to store negative numbers. For negative numbers, sign bit (MSB) is 1 in this form which is padded during the operation. Using unsigned number will fix the issue.