算数位移和逻辑位移

本文详细解释了逻辑位移和算数位移的概念及其在不同编程语言中的应用,如Java和C语言。阐述了位移操作在汇编层面的不同指令,并讨论了在C标准中对于有符号和无符号数据位移的定义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

逻辑位移是移动数字的所有物理比特位。

算数位移是对数字除了符号位以外的比特位进行位移,符号位保持不变。

当具体到以二进制补码表示的负数的方式上,算数位移的表现形式就是在最高位补1.
当然你还没有学到二进制补码。马上就快了。

如果负数的表示形式不是二进制补码(这很少见),那算数位移就不一定是在最高位补1.

在汇编层面上,算数位移和逻辑位移是两条不同的指令。
在java语言中,使用>>>表示逻辑位移,使用>>表示算数位移,所以即使是有符号数,也可以做逻辑位移
在C语言中,只有>>表示位移。对于有符号数,通常(但不是绝对)使用的是算数位移。

“无符号数就是逻辑,有符号数就是算数”,这个推论是不严谨的。虽然绝大多数情况下是正确的。

“The C standard does not precisely define which type of right shift should be used. For unsigned data (i.e.,
integral objects declared with the qualifier unsigned), right shifts must be logical. For signed data (the
default), either arithmetic or logical shifts may be used. This unfortunately means that any code assuming
one form or the other will potentially encounter portability problems. In practice, however, almost all
compiler/machine combinations use arithmetic right shifts for signed data, and many programmers assume
this to be the case."

CSAPP 2.1.10里面清楚的写了。

For signed data (the default), either arithmetic or logical shifts may be used.

看完书,不等于看懂书。一本CSAPP你能半年学透了都是很不错的成绩了。

转载于:https://www.cnblogs.com/aoaoblogs/p/8003959.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值