This question already has an answer here:
I get a different result depending on if I combine multiple bitwise shifts on one line or put them on separate lines.
unsigned char a = 73;
a = (a << 6) >> 2;
printf("%d\n", a);
prints 144 when I expect 16
unsigned char a = 73;
a = a << 6;
a = a >> 2;
printf("%d\n", a);
prints the expected result of 16
when I shift left 6, then right 1 on one line, it prints the expected result of 32, so it looks like the 2nd shift right is shifting in a 1 instead of a 0, but why?
Also
a = (unsigned char) (a << 6 ) >> 2;
produces the expected result (16).
Is the first left shift returning a signed char instead of an unsigned char, and if so why?
Yes, the result of the first shift is signed. signed int specifically. Check out the rules for the "integer promotions" in the C spec:
If an
intcan represent all values of the original type ... the value is converted to anint...
So, since your int - usually a range of [-231, 231) - can represent all the values of unsigned char - usually [0, 255] - it's converted to int, and the << and >> take place on the resulting values.
来源:https://stackoverflow.com/questions/25393058/unexepected-behavior-from-multiple-bitwise-shifts-on-the-same-line