使用SAR与SHR在汇编中将二进制数右移 [英] shifting a binary number to the right in assembly with SAR vs. SHR

查看:158
本文介绍了使用SAR与SHR在汇编中将二进制数右移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,当我们向右移动二进制数时,它会被2除. 对于数字:1001 0001.假设它存储在AX寄存器中:

We know that when we shift a binary number to the right, it is divided by 2. For the number: 1001 0001. Let's assume that is stored in AX register:

  • 如果我们将其视为无符号数字(等于十进制的145): SHR AX, 1将使AX等于0100 1000,其等于十进制的72,这是正确的.

  • If we consider it as unsigned number (which is equal to 145 in decimal): SHR AX, 1 will make AX equal to 0100 1000 which is equal to 72 in decimal, and this is right.

但是,如果我们将其视为带符号的数字(十进制等于-111):SAR AX, 1将使AX等于1100 0100等于十进制-56,并且这是错误的,因为它应等于十进制的-55.

But if we consider it as signed number (which is equal to -111 in decimal): SAR AX, 1 will make AX equal to 1100 0100 which is equal to -56 in decimal, and this is wrong because it should be equal to -55 in decimal.

为什么?

推荐答案

SHR指令执行无符号移位权,移位为零:

The SHR instruction performs an unsigned shift rights, shifting in zeros:

Input:  1001 0001
        |      |\
        +------+ +--> lost
            v
         +------+
         |      |
Output: 0100 1000
        ^
        +-- added by SHR

另一方面,SAR指令执行带符号右移,将最高有效位解释为符号.它会移动符号位的副本:

On the other hand, the SAR instruction performs a signed shift right, interpreting the most significant bit as a sign. It shifts in copies of the sign bit:

Input:  1001 0001
        |      |\
        +------+ +--> lost
        |   v
        |+------+
        v|      |
Output: 1100 1000
        ^
        +-- preserved (copied) by SAR

这篇关于使用SAR与SHR在汇编中将二进制数右移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆