移位运算及其compiler-dependent

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.

具体代码示例:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值