算数位移和逻辑位移

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

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

当具体到以二进制补码表示的负数的方式上,算数位移的表现形式就是在最高位补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你能半年学透了都是很不错的成绩了。

posted @ 2017-12-08 09:41  嗷嗷  阅读(3149)  评论(0编辑  收藏  举报