Unexepected behavior from multiple bitwise shifts on the same line [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-02 04:28:44

问题


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?


回答1:


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 int can represent all values of the original type ... the value is converted to an int...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!