C中的移位操作,其实内容不太多,但是有一些小的细节,需要注意,以便碰到特定问题,我们能有思路去分析。
移位操作主要分为: Shift(Left, Right),Circular Shift(Left, Right)。从移位的性质看,主要分为:逻辑移位,算数移位。
一、算数移位 VS 逻辑移位
二者核心区别就是对符号位的处理,算术移位是考虑符号位的,逻辑移位不考虑符号位,直接进行移位。即算数移位:空缺位补符号位;逻辑移位:空缺位补0,忽略符号特性。
二、左移和右移的处理
下面用摘自 stackoverflow 的一段话来说明:
When shifting left, there is no difference between arithmetic and logical shift. When shifting right, the type of shift depends on the type of the value being shifted.
(As background for those readers unfamiliar with the difference, a "logical" right shift by 1 bit shifts all the bits to the right and fills in the leftmost bit with a 0. An "arithmetic" shift leaves the original value in the leftmost bit. The difference becomes important when dealing with negative numbers.)
Many C compilers choose which right shift to perform depending on what type of integer is being shifted; often signed integers are shifted using the arithmetic shift, and unsigned integers are shifted using the logical shift.
具体代码示例: