What the result of code below:
char ch = 0x80;
printf("char after shift: ch >> 2 = %d\n", ch>>2);
I thought it maybe 32 cause I didn't notice there is a big difference between signed and unsigned char while shifting.
The right answer is -32. Here is the reason:
Char will be converted into an int while bit-shifting. So when it's a negative number, the higher three bytes will be filled up with 1. Those 1 are pulled in while shifting right. So 0x80 becomes 0xe0, and it's -32.
But refer to C89, the conclusion above is not absolutely right. It's implementation-defined.
Quote Originally Posted by C89
The result of E1 >> E2 is E1 right-shifted E2 bit positions.
If E1 has an unsigned type or if E1 has a signed type and a nonnegative value,
the value of the result is the integral part of the quotient of E1 divided by the quantity,
2 raised to the power E2. If E1 has a signed type and a negative value,
the resulting value is implementation-defined.
So remember to use unsigned char if you want to do a right shift.